This is a question related to date and time when implementing a bulletin board post.

Asked 2 years ago, Updated 2 years ago, 92 views

    SimpleDateFormat qqqq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    SimpleDateFormat zxcv = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    zxcv.setTimeZone(TimeZone.getTimeZone("UTC"));
    final Date zz = new Date();
    try {
        Date xxx = zxcv.parse("2016-10-31T08:25:24.000Z");
        String vvvv = qqqq.format(xxx);

        long subtract = zz.getTime() - xxx.getTime(); // comes as a millisecond value
        month = (subtract/1000/60/60/24/30);
        day = (subtract/1000/60/60/24);
        hour = (subtract/1000/60/60);
        minute = (subtract/1000/60);

    } } catch (ParseException e) {
        e.printStackTrace();
    }

I tried it like this, and the subtract value came out in milliseconds, so I implemented long month, day, hour, minute like that. By the way, the larger the subtract value (time difference), the more minutes are supposed to exceed 60 minutes, and the more hours are supposed to exceed 24 hours, but what should I do to make it automatic when the minutes exceed 60 minutes?

date time android json

2022-09-21 18:43

1 Answers

Please test it with the code below.

public void printDifference(Date startDate, Date endDate) {
    //milliseconds
    long different = endDate.getTime() - startDate.getTime();

    System.out.println("startDate : " + startDate);
    System.out.println("endDate : "+ endDate);
    System.out.println("different : " + different);

    long secondsInMilli = 1000;
    long minutesInMilli = secondsInMilli * 60;
    long hoursInMilli = minutesInMilli * 60;
    long daysInMilli = hoursInMilli * 24;

    long elapsedDays = different / daysInMilli;
    different = different % daysInMilli;

    long elapsedHours = different / hoursInMilli;
    different = different % hoursInMilli;

    long elapsedMinutes = different / minutesInMilli;
    different = different % minutesInMilli;

    long elapsedSeconds = different / secondsInMilli;

    System.out.printf(
        "%d days, %d hours, %d minutes, %d seconds%n", 
        elapsedDays,
        elapsedHours, elapsedMinutes, elapsedSeconds);
}

Source


2022-09-21 18:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.