How to calculate Time ago in in java(jsp) - java

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"

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:
Introduction to the Java 8 Date/Time API
Java 8: Difference between two LocalDateTime in multiple units

Related

Get 1 year back dateTime from current dateTime in yyyy-MM-dd HH:mm:ss.SSS format

I need to get the datetime of 1 year back considering the current datetime. The format needed to be in "yyyy-MM-dd HH:mm:ss.SSS"
ex : 2019-08-13 12:00:14.326
I tried following. But getting an error.
LocalDate now = LocalDate.now();
LocalDate localDate = LocalDate.parse(now.toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")).minusYears(1);
Below Exception returned:
DateTimeParseException: Text '2020-08-13' could not be parsed
What's the best way to do this in Java 8+ ?
A LocalDate does not hold any information about hours, minutes, seconds or any unit below, instead, it holds information about year, month and day. By calling LocalDate.now() you are getting the date of today (the day of code execution).
If you need the time as well, use a LocalDateTime, which has a method now(), too, and actually consists of a LocalDate and a LocalTime.
Your error message tells you that the content of a LocalDate cannot be formatted using the given pattern (-String) "yyyy-MM-dd HH:mm:ss.SSS" because that pattern requires values for hours (HH), minutes (mm), seconds (ss) and milliseconds (SSS are fraction of seconds and three of them make it be milliseconds).
For parsing Strings or formatting datetimes, a LocalDateTime may be suitable but if you want to reliably add or subtract a year or any other amount of time, you'd rather use a class that considers time zones, offsets and daylight saving like ZonedDateTime or OffsetDateTime...
The LocalDate is the wrong class for your requirement as it does not hold the time information. You can use LocalDateTime but I suggest you use OffsetDateTime or ZonedDateTime so that you can get the flexibility of using the Zone Offset and Zone ID. Check https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html for an overview of date-time classes.
Also, keep in mind that a date or time or date-time object is an object that just holds the information about date/time; it doesn't hold any information about formatting and therefore no matter what you do when you print their objects, you will always get the output what their toString() methods return. In order to format these classes or in other words, to get a string representing a custom format of these objects, you have formatting API (e.g. the modern DateTimeFormatter or legacy SimpleDateFormat) at your disposal.
A sample code:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Get the current date & time at UTC
OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println("Now at UTC: " + odtNow);
// Get the date & time one year ago from now at UTC
OffsetDateTime odtOneYearAgo = odtNow.minusYears(1);
System.out.println("One year ago at UTC: " + odtNow);
// Define a formatter for the output in the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
// Format the date & time using your defined formatter
String formattedDateTimeOneYearAgo = formatter.format(odtOneYearAgo);
System.out.println("Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: " + formattedDateTimeOneYearAgo);
}
}
Output:
Now at UTC: 2020-08-13T08:50:36.277895Z
One year ago at UTC: 2020-08-13T08:50:36.277895Z
Date Time in the pattern, yyyy-MM-dd HH:mm:ss.SSS: 2019-08-13 08:50:36.277
May not be the best way, but this will do it
LocalDateTime date = LocalDateTime.now().minusYears(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(date.format(formatter));
You say you want date+time from 1 year back, but you give it only a date (LocalDate). If you just want the date, all you need to do is:
LocalDate now = LocalDate.now();
LocalDate then = now.minusYears(1);
And if you want the timestamp also, then:
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.minusYears(1);
And so on for other objects.
As mentioned you should use LocalDateTime instead of LocalDate.
Your exception was thrown because your input String is in ISO_DATE_TIME format
Java Doc
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String now = dateTimeFormatter.format(LocalDateTime.now());
LocalDateTime localDate = LocalDateTime.parse(now, dateTimeFormatter);

Convert milliseconds to timestamp with UTC

I'm trying to convert milliseconds to Timestamp with timezone UTC but it doesn't work as is expected because it convert to my localdatetime.
I have tried following. While debugging the code I have found that when execute this: new DateTime(eventDate) it is working properly because it's value is 10:34:18.721 but later new Timestamp() change it to localdatetime.
long eventDate = 1566297258721L;
DateTimeZone.setDefault(DateTimeZone.UTC);
Timestamp timestamp = new Timestamp(new DateTime(eventDate).getMillis());
I expect to output as:2019-08-20 10:34:18.721 but actual output is: 2019-08-20 12:34:18.721
You can use java.time package of Java 8 and later:
ZonedDateTime zonedDateTime = Instant.ofEpochMilli(1566817891743L).atZone(ZoneOffset.UTC);
I don't understand why you are creating a new DateTime and then get the milliseconds from there, if you already have the milliseconds in the beginning.
Maybe I'm misunderstanding your problem. The milliseconds have nothing to do with the timezone. The timezone is used to compare the same moment in 2 different places and get the respective date. Here are my solutions
If you want a timestamp from milliseconds:
long eventDate = 1566297258721L;
Timestamp time=new Timestamp(eventDate);
System.out.println(time);
The result would be 2019-08-20 10:34:18.721 , also the wished SQL format
If you want to convert a moment from a Timezone to another:
You will get the moment in your actual timezone and transform it in a different one in order to see e.g. what time it was in an other country
long eventDate = 1566297258721L;
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.format(calendar.getTime());
I hope those snippets could be useful. Happy Programming!
You can try the following,
long eventDate = 1566297258721L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String stringDate = simpleDateFormat.format(new Date(eventDate));
System.out.println(stringDate);
It gives me the following output.
2019-08-20 10:34:18 UTC

Converting from String to specific HH:mm date format

I have a String object which stores the current system time in HH:mm format. I have to convert this to a DATE object and maintain the same HH:mm format. How can this be done.
I tried using Date parse options but everytime I get the response in complete dd-MM-yyyy HH:mm:ss format and not in the required HH:mm format needed.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String getCurrentTime = sdf.format(Calendar.getInstance().getTime());
Date date = sdf1.parse(getCurrentTime);
Expected output should be a Date result in HH:mm format.
Like mentioned in the comments, Date is an object. Other way around with Date/Time API:
LocalTime time = LocalTime.now(); //current time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); //set format
System.out.println(time.format(formatter));
Here is the simple example to solve this using java8 Date and Time API:
DateTimeFormatter parser1 = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime ldd1 = LocalDateTime.now();
System.out.println("DateTimeFormatter ldd1 = " + parser1.format(ldd1));
You are expecting the output of parse to be a Date object in format HH:mm but this will never be the case because it is eventually a Date object. It will have information of date,month,year, time etc i.e. it is made to store both date and time information.
You get the information HH:mm using the format method which you did and it does give you that information
If you want only information of Hour and minutes, I suggest you to create a new class and populate it's value based on output of format method
Instead of using Date use java.time.LocalTime. Example:
LocalTime localTime = LocalTime.now();
This class does not store and represent a date or time-zone. You can use the LocalTime.now() and LocalTime.of() methods to create the current time and specific time object respectively.
You can use the getHour(), getMinute() and getSecond() methods of the LocalTime class to get hour, minute and second respectively.
You can use the plus and minus methods of the LocalTime class to add or subtract hours, minutes etc.
You can use the compareTo(), isAfter() and isBefore() methods of the LocalTime class to compare the LocalTime objects.

Subtract char of digits like normal integers

I have two strings which can be seen as time stamps:
String min="2017-04-15 13:27:31";
String max="2017-04-15 13:40:01";
Assume we want to find out the time passed from first time stamp to the second one. If there was only the time and no date included, I could get it using my following code:
String[] partsMin=min.split(":");
String[] partMax=max.split(":");
int diffZero=Integer.parseInt(partMax[0])-Integer.parseInt(partsMin[0]);
int diffOne=Integer.parseInt(partMax[1])-Integer.parseInt(partsMin[1]);
int diffOTwo=Integer.parseInt(partMax[2])-Integer.parseInt(partsMin[2]);
diffInSec=diffZero*3600+diffOne*60+diffOTwo;
So here is the question. How to get the job done while there is a date within the time stamp?
I would construct LocalDateTime instances from it.
Then i would get the milliseconds from it and substract startTime from EndTime.
What is remaining are the milliseconds passed between the two. A DateTimeFormatter is helpful as well for this purpose.
String strMin = "2017-04-15 13:27:31";
DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(strMin, formatter);
String strMax = "2017-04-15 13:40:01";
LocalDateTime dateTimeMax = LocalDateTime.parse(strMax, formatter);
long minutes = ChronoUnit.MINUTES.between(dateMin, dateMaxto);
long hours = ChronoUnit.HOURS.between(dateMin, dateMax);
If you want to get the milliseconds:
long millisPassed = dateMax.toEpochMilli() - dateMax.toEpochMilli();
Use the java date time libraries (even the old Date class would be fine for this) to parse the string into a proper object.
Depending on the date time library you chose you can then look at the difference between them. The simplest would be something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = sdf.parse(str1);
Date date2 = sdf.parse(str2);
long differenceInSeconds = (date2.getTime()-date1.getTime())/1000;
The new Java 8 time classes would also allow you to do this and would be better to learn going forwards. I can't remember the syntax for that off the top of my head though.
Did you try with replace all the other part of your String like this :
String[] partsMin = min.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
String[] partMax = max.replaceAll("\\d+-\\d+-\\d+", "").trim().split(":");
Doing this in your code:
int diffZero=Integer.parseInt(partMax[0])
is the same as doing:
int diffZero=Integer.parseInt("2017-04-15")
that is generating an Exception(NumberFormatException)
you should better try to PARSE those strings min and max into a date
Edit:
you can inspect your code/ variables: and see that splitting to ":" is not giving you back the correct array since the element at index 0 is holding more information than you need...
but as I said before, you are going on the wrong path, dont re invent the wheel and look how practical will get using the APIs that java has for us:
String min = "2017-04-15 13:27:31";
String max = "2017-04-15 13:40:01";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTimeMin = LocalDateTime.parse(min, formatter);
LocalDateTime dateTimeMax = LocalDateTime.parse(max, formatter);
long days = ChronoUnit.DAYS.between(dateTimeMin, dateTimeMax);
long minutes = ChronoUnit.MINUTES.between(dateTimeMin, dateTimeMax);
System.out.println(days);
System.out.println(minutes);
use SimpleDateFormat to parse the date string, and do operation on Date result, you will get right value. This works well for date between '2017-02-28 23:59:59' and '2017-03-01 00:00:01'
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = format.parse("2017-02-28 23:59:59");
Date date2 = format.parse("2017-03-01 00:00:01");
long time1 = date1.getTime();
long time2 = date2.getTime();
long diff = time2 - time2; // should be 2000

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

I have an external API that returns me dates as longs, represented as milliseconds since the beginning of the Epoch.
With the old style Java API, I would simply construct a Date from it with
Date myDate = new Date(startDateLong)
What is the equivalent in Java 8's LocalDate/LocalDateTime classes?
I am interested in converting the point in time represented by the long to a LocalDate in my current local timezone.
If you have the milliseconds since the Epoch and want to convert them to a local date using the current local timezone, you can use Instant.ofEpochMilli(long epochMilli)
LocalDate date =
Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate();
but keep in mind that even the system’s default time zone may change, thus the same long value may produce different result in subsequent runs, even on the same machine.
Further, keep in mind that LocalDate, unlike java.util.Date, really represents a date, not a date and time.
Otherwise, you may use a LocalDateTime:
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
You can start with Instant.ofEpochMilli(long):
LocalDate date =
Instant.ofEpochMilli(startDateLong)
.atZone(ZoneId.systemDefault())
.toLocalDate();
I think I have a better answer.
new Timestamp(longEpochTime).toLocalDateTime();
Timezones and stuff aside, a very simple alternative to new Date(startDateLong) could be LocalDate.ofEpochDay(startDateLong / 86400000L)
A simple version based on #Michael Piefel answer:
LocalDate myDate = LocalDate.ofEpochDay(Duration.ofMillis(epochMillis).toDays());
replace now.getTime() with your long value.
//GET UTC time for current date
Date now= new Date();
//LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
I have tested this alternative solution for LocalDateTime:
public static LocalDateTime increaseByMillis(final LocalDateTime ldt, final long millis)
{
return LocalDateTime.ofInstant(Instant.ofEpochMilli(ldt.toInstant(ZoneOffset.UTC).toEpochMilli()+millis), ZoneId.of(ZoneOffset.UTC.getId()));
}
Test:
LocalDateTime test = LocalDateTime.now();
LocalDateTime increased = MyUtilsAbc.increaseByMillis(test, 1000);
Assert.assertEquals("Increase of LocalDateTime not working (anymore)!", test.toEpochSecond(ZoneOffset.UTC) +1, increased.toEpochSecond(ZoneOffset.UTC));
In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:
long startDateLong = <...>
LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();

Categories

Resources