Home > Net >  Calculate Number of Days between Given time in ISO format and Current time
Calculate Number of Days between Given time in ISO format and Current time

Time:09-22

I have to find out number of days between a given Time and current time. Given time is in ISO format and one example is "2021-01-14 16:23:46.217-06:00".

I have tried it using "java.text.SimpleDateFormat" but it's not giving me accurate results.
In Below Given date, for today's time I am getting output as "633" Days which isn't correct. somehow after parsing it is taking date as "21 december 2020" which isn't correct

String TIMESTAMP_FORMAT = "YYYY-MM-DD hh:mm:ss.s-hh:mm" ;  
int noOfDays = Utility.getTimeDifferenceInDays("2021-01-14 16:23:46.217-06:00", TIMESTAMP_FORMAT);
              
public static int getTimeDifferenceInDays(String timestamp, String TIMESTAMP_FORMAT) {

        DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
        try {
            Date date = df.parse(timestamp);
            long timeDifference = (System.currentTimeMillis() - date.getTime());
            return (int) (timeDifference / (1000*60*60*24));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }  

Looking for a better solution which gives me correct number of days. Thanks

CodePudding user response:

Use java.time API

Classes Date and SimpleDateFormat are obsolete.

Since Java 8 (which was released 10 years ago) we have a new Time API, represented by classes from the java.time package.

To parse and format the data you can use DateTimeFormatter. An instance of DateTimeFormatter can be obtained via static method ofPattern(), or using DateTimeFormatterBuilder.

  • ofPattern():
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSXXX");
  • DateTimeFormatterBuilder:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd HH:mm:ss.")       // main date-time part
    .appendValue(ChronoField.MILLI_OF_SECOND, 3) // fraction part of second
    .appendOffset(" HH:MM", " 00:00")            // can be substituted with appendPattern("zzz") or appendPattern("XXX")
    .toFormatter();

The string "2021-01-14 16:23:46.217-06:00", which you've provided as an example, contains date-time information and UTC offset. Such data can be represented by OffsetDateTime.

To get the number of days between two temporal objects, you can use ChronoUnit.between() as @MC Emperor has mentioned in the comments.

That's how the whole code might look like:

String toParse = "2021-01-14 16:23:46.217-06:00";


    
OffsetDateTime dateTime = OffsetDateTime.parse(toParse, formatter);
System.out.println("parsed date-time: "   dateTime);
        
Instant now = Instant.now();
        
long days = ChronoUnit.DAYS.between(dateTime.toInstant(), now);
System.out.println("days: "   days);

Output:

parsed date-time: 2021-01-14T16:23:46.217-06:00
days: 615

Note that since in this case you need only difference in days between the current date instead of OffsetDateTime you can use LocalDateTime, UTC offset would be ignored while parsing a string. If you decide to do so, then the second argument passed to ChronoUnit.between() should be also of type LocalDateTime.

  • Related