-1

friends im new using date and time in java. I stored date and time in String which is the current time similarly I have one more string variable which has the post time now I want to calculate the ago time even in seconds on any the string has date and time in this format yyyy/MM/dd HH:mm:ss can some one help me Thank you here is the code

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

        LocalDateTime currentTime = LocalDateTime.parse(d_tt, formatter);
        LocalDateTime postTime = LocalDateTime.parse(post_time, formatter);

        long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);//(error here)

error "ChronoUnit cannot be resolved"

Education 4Fun
  • 176
  • 3
  • 16
  • 1
    Does this answer your question? [Do we have a TimeSpan sort of class in Java](https://stackoverflow.com/questions/6581605/do-we-have-a-timespan-sort-of-class-in-java) – Clijsters Jul 06 '20 at 12:34
  • 1
    Does this answer your question? [How to calculate time difference in java?](https://stackoverflow.com/questions/4927856/how-to-calculate-time-difference-in-java) – Paul Jul 06 '20 at 12:42

1 Answers1

1

For this case it is best to use LocalDateTime.

First you have to convert the two strings into a LocalDateTime

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");

LocalDateTime currentTime = LocalDateTime.parse(currentTimeString, formatter); // Or use LocalDateTime.now()
LocalDateTime postTime = LocalDateTime.parse(postTimeString, formatter);

These objects can then be used to determine the time between them. There are two possibilities to do this. All of them give the same result, which you can use to determine the time between them according to your own preferences.

Possibility 1:

long seconds = postTime.until(currentTime, ChronoUnit.SECONDS);

Possibility 1:

long seconds = ChronoUnit.SECONDS.between(postTime, currentTime);

You can also get more information here:

  1. Introduction to the Java 8 Date/Time API
  2. Java 8: Difference between two LocalDateTime in multiple units
tgallei
  • 827
  • 3
  • 13
  • 22