PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 14, 2022

[FIXED] How to calculate Time ago in in java(jsp)

 July 14, 2022     java, jsp, web-deployment     No comments   

Issue

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"


Solution

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


Answered By - tgallei
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing