This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 4 years ago.
How can I get UTC value in Java of any given time and date with the respective time-zone?
Say for example my current time zone is Asia/Kolkata, now how can I get UTC value of say 1.00 am on 21/07/2018?
For getting currect time in UTC.
Instant.now() // Current time in UTC.
For getting current time in any desired TimeZone.
ZonedDateTime.now( ZoneId.systemDefault() ) // Current time in your ZoneId.
Kolkata Example :
ZoneId zoneKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
To adjust back to UTC, extract an Instant from the ZonedDateTime.
Instant instant = zoneDTKolkata.toInstant() ;
You can adjust from UTC to a time zone.
ZonedDateTime zoneDTKolkata = instant.atZone( zoneKolkata ) ;
Use the Java 8 time API instead of the older API (ie Date & SimpleDateFormat solution proposed by rajadilipkolli)
// System time (ie, your operating system time zone)
LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, minute, second);
// Time in Asia/Kolkata
ZonedDateTime kolkata = ldt.atZone(ZoneId.of("Asia/Kolkata"));
// Time in UTC
OffsetDateTime utc = ldt.atOffset(ZoneOffset.UTC);
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h.mm a 'on' dd/MM/uuuu")
.toFormatter(Locale.ENGLISH);
ZoneId zone = ZoneId.of("Asia/Kolkata");
String localDateTimeString = "1.00 am on 21/07/2018";
Instant i = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant();
System.out.println("UTC value is: " + i);
This prints:
UTC value is: 2018-07-20T19:30:00Z
I wasn’t sure whether you needed to parse the exact string you gave, 1.00 am on 21/07/2018, into a date-time object, but in case I have shown how. The challenge is that am is in lowercase. In order to specify case insensitive parsing I needed to go through a DateTimeFormatterBuilder.
As you can see, the code converts to an Instant, which is the modern way to represent a point in time in Java. Instant.toString always prints the time in UTC. The Z at the end means UTC. If you want a date-time that is more explicitly in UTC you may use
OffsetDateTime odt = LocalDateTime.parse(localDateTimeString, formatter)
.atZone(zone)
.toInstant()
.atOffset(ZoneOffset.UTC);
System.out.println("UTC value is: " + odt);
The output is similar, only OffsetDateTime leaves out the seconds if they are 0 (zero):
UTC value is: 2018-07-20T19:30Z
Link: Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.
Related
LocalDate beginDate = LocalDate.now()
.with(ChronoField.DAY_OF_WEEK, 1)
.atStartOfDay()
.minusDays(8)
.toLocalDate();
I am getting the previous week begin date using the above code line. However I want to add HH:MM:SS format to this. I have tried different ways to get this. Tried using LocalDateTime instead of Localdate. But could not find atStartOfDay() method for LocalDateTime. Help me to add HH:MM:SS to beginDate variable
tl;dr
LocalDate // Represents a date only, without a time of day, without a time zone or offset.
.now( ZoneId.of( "Asia/Amman" ) ) // Returns a `LocalDate`.
.minusDays( 8 ) // Returns another `LocalDate` object.
.atStartOfDay( ZoneId.of( "Asia/Amman" ) ) // Returns a `ZonedDateTime`.
.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets.
See this code run at Ideone.com. Notice that on that date in that zone, the day began at 01:00, not 00:00.
2022-02-22T01:00+03:00[Asia/Amman]
No “format” involved
Date-time objects do not have a “format”. Text has a format. Date-time objects are not text.
LocalDate has no time of day
You said:
add HH:MM:SS format to [a LocalDate object]
A LocalDate represents a date only, without a time of day, without a time zone or offset.
ZonedDateTime
Apparently you want the first moment of the day eight days ago as seen in your locality.
First, specify your desired/expected time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
Or use your JVM‘s current default time zone.
ZoneId z = ZoneId.systemDefault() ;
Capture the current date as seen in that zone.
LocalDate today = LocalDate.now( z ) ;
Go back eight days.
LocalDate eightDaysAgo = today.minusDays( 8 ) ;
If you meant to go back to the previous Monday, use a TemporalAdjuster.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;
Get the first moment of that day. Pass your time zone.
ZonedDateTime zdt = eightDaysAgo.atStartOfDay( z ) ;
The time-of-day may be 00:00:00, but not necessarily. Some days on some dates in some zones start at another time such as 01:00:00.
All of this has been covered many times already on Stack Overflow. Search to learn more.
What you want is a LocalDateTime, which is a LocalDate with a time component (including timezone).
LocalDate does as it says on the tin, it gives you a date, not a date and time.
LocalDateTime
.of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)
.minusWeeks(1)
Gives you start of last week at midnight (local time).
#DateTimeFormat("HH:MM:SS")
#JsonFormat("HH:MM:SS")
I need to do a LocalDateTime conversion of a UTC date to another LocalDateTime variable considering a specific timezone tz.
During my research I found many solutions, but they all convert the LocalDateTime to another type, like ZonedDateTime.
I need something like that, but LocalDateTime wont work with ZoneId:
LocalDateTime output = input.getInitDate().of(ZoneId.of(tz))
Considering a -3 timezone:
input: 2019-12-03T18:24:07
output: 2019-12-03T15:24:07
Your Question makes no sense.
You need to understand that LocalDateTime holds nothing but a date and a time-of-day. The class purposely lacks any concept of time zone or offset-from-UTC. So LocalDateTime does not represent a moment. The name can be misleading, as a LocalDateTime is not about any particular locality.
If you want to track a moment in UTC, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC. Always in UTC, by definition.
If you want to track a moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montevideo" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
LocalDateTime conversion of a UTC date
Do you mean you have particular date and time in mind as seen at the prime meridian? Or as seen in Iceland which uses UTC as their time zone?
LocalDate ld = LocalDate.of( 2020 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 0 ) ; // 3 PM.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
This ldt object means "3 PM on the 23rd of January this year" somewhere, or anywhere. But that LocalDateTime object does not 3 PM in one particular place. We have no idea if the intention here is 3 PM in Tokyo Japan or 3 PM in Toulouse France or 3 PM in Toledo Ohio US. Those would be three different moments, several hours apart. A LocalDateTime represents none of them, or all of them, whichever way you want to see it, but not any one of them.
To determine a moment from a date and a time-of-day, you need the context of a time zone or offset-from-UTC. In other words the third piece of information, in addition to the date and the time-of-day, we need is "as seen in Paris France" or "as seen in Palmer Station in Antarctica". With such a context, we get either ZonedDateTime or OffsetDateTime, respectively.
ZoneId z = ZoneId.of( "Antarctica/Palmer" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ldt , z ) ; // Giving context of time zone to the date-with-time `LocalDateTime` object. Determines a moment.
To see that same moment in UTC (an offset of zero hours-minutes-seconds), extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC.
Time zone versus offset-from-UTC
Considering a -3 timezone:
No, -3 is not a time zone, it is an offset.
The -3 is short for -03:00. Practically speaking, I suggest you avoid abbreviating the offset as some libraries expect a full hours-with-minutes including the colon character, and including the leading zero on single-digit hours or minutes.
The -3 or -03:00 means simply "three hours behind UTC".
A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. A time zone has a name in the form of Continent/Region such as Africa/Tunis or Europe/Paris.
See the list of time zones on Wikipedia. Sort by offset column. Notice how around three dozen time zones may today be sharing the offset of -03:00 such as America/Montevideo, Atlantic/Stanley, and Antarctica/Palmer.
Always prefer a time zone to a mere offset. When doing date-time math and adding/subracting spans of time, the results may vary by time zone. Time zones may be using different offsets other than -03:00 on other dates in the past and in the future.
You need to convert it first to ZonedDateTime, change the timezone, and then extract LocalDateTime from that:
ZoneId from = ...;
ZoneId to = ...;
LocalDateTime input = ...;
LocalDateTime output = input.atZone(from).withZoneSameInstant(to).toLocalDateTime();
Try this solution:
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);
ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneId.of("UTC-3"));
System.out.println(utcZoned.toLocalDateTime());
It gives the output:
2020-02-03T20:55:33.313882
2020-02-03T17:55:33.313882
got a little problem in Java: I've got two strings, representing a date (for example "2019-11-10") and a time (for example "01:23:45.123"). Converting those into a UTC timestamp is easy enough, but there is one problem:
The date is given in a local timezone, for example "America/New_York", while the time is given in UTC, so the following information...
date = "2019-11-10", time="01:23:45.123" (assuming a local timezone of "America/New_York" for the date part)
...would actually be the UTC time "2019-11-11 01:23:45.123" (since only this would be a New York date of "2019-11-10").
Does the Java Time API or joda time offer any convenient method to do this conversion while keeping also details like DST, etc. in mind? Is there a (relatively) simple way of doing this at all?
Edit:
Perhaps this was a bit unclear. Let me try to explain it from the other side:
Assuming I have a DateTime x (in UTC) of "2019-11-11 01:23:45.123".
Then I can get the date part y (as seen in "America/New_York") by simply converting x into the appropriate timezone and formatting is accordingly -> "2019-11-10".
I can also get the time part z (as seen in UTC) by simply formatting is accordingly - "01:23:45.123".
Now, assuming I've got y and z - How do I get x?
Edit 2:
I just realized, this will never work perfectly. Reason:
UTC "2019-11-04 04:01:00.000" -> US/NY : "2019-11-03 23:01"
UTC "2019-11-03 04:01:00.000" -> US/NY : "2019-11-03 00:01"
So, if I only got the information "date in US/NY" is "2019-11-03" plus "time in UTC" is "04:01:00.000" there are actually two possible solutions and not only one.
You have to adjust the date to be in the New York time zone which can be done by choosing an arbitrary time. Then convert the time to New York by choosing an arbitrary date. The two can then be merged as they have the same zone. And convert back to UTC
LocalDate date = LocalDate.parse("2019-11-10");
LocalTime time = LocalTime.parse("01:23:45.123");
ZoneId zone = ZoneId.of("America/New_York");
ZonedDateTime dateInZone = date.atStartOfDay(zone);
ZonedDateTime timeInZone = time.atOffset(ZoneOffset.UTC).atDate(date).atZoneSameInstant(zone);
ZonedDateTime resultNY = dateInZone.with(timeInZone.toLocalTime());
ZonedDateTime resultUTC = resultNY.withZoneSameInstant(ZoneOffset.UTC)
System.out.println(resultUTC);
// 2019-11-11T01:23:45.123Z
A date cannot have a time zone. (Think about it.)
Perhaps what you mean is the first moment of the day for that date as seen in UTC.
LocalDate ld = LocalDate.parse( "2019-11-10" ) ;
ZonedDateTime zdt = ld.atStartOfDay( ZoneOffset.UTC ) ;
Adjust that moment to be seen in a time zone.
ZoneId z = ZoneId.of( "America/New_York" ) ;
LocalTime lt = LocalTime.parse( "01:23:45.123" ) ;
ZonedDateTime zdt2 = zdt.with( lt ) ;
I'm getting start date as "2016-06-01" and end date as "2016-07-01" (in string format) for searching records in MongoDB. Need pointer/guidance to append start time (00:00:00.000) to start date and maximum time(23.59.59.999) to end date as below in Java using java.util.Date or any others which supported by MongoDB.
Example :
Start Date+with time : 2016-06-01T00:00:00.000
End Date+with time : 2016-07-01T23:59:59.999
You could use the DateTimeFormatter.ISO_LOCAL_DATE_TIME for this. Here is an example that might shed some light on what you are trying to do:
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
String startTime = "T00:00:00.000";
String endTime = "T23:59:59.999";
//here I used the LocalDateTime parser to parse the data+startTime/endTime
LocalDateTime startLocalDateTime = LocalDateTime.parse("2016-07-01"+startTime);
LocalDateTime endLocalDateTime = LocalDateTime.parse("2016-07-01"+endTime );
//with the LocalDateTime, you can then to whatever you want
//as an example, I am parsing it using ISO_LOCAL_DATE_TIME :
String strinStartTime= dtf.format(LocalDateTime.parse("2016-07-22"+startTime));
I hope this helps;
tl;dr
ZoneId zoneId = ZoneId.of( "Europe/Paris" ) ;
LocalDate startDate = LocalDate.of( "2016-06-01" ) ;
ZonedDateTime zdt start = startDate.atStartOfDay( zoneId ) ;
ZonedDateTime zdt stop = startDate.plusMonths(1).atStartOfDay( zoneId ) ;
// Perform database search where ( ( x >= start ) AND ( x < stop ) ) . Notice '>=' versus '<' with no 'equals' on the latter.
If you need strings…
String outputStart = start.toInstant().toString() ; // 2016-05-31T22:00:00Z Paris in the summer is two hours ahead of UTC.
String outputStop = stop.toInstant().toString() ; // 2016-06-30T22:00:00Z
Details
The Answer by ishmaelMakitla is good in that it points to using the java.time classes built into Java 8 and later. But it focuses on strings rather than objects. Also it does not discuss the crucial issue of time zone.
The java.time classes include:
LocalDate for a date-only value with no time-of-day and no time zone.
LocalTime for a time-of-day value without a date and without a time zone.
LocalDate startDate = LocalDate.parse( "2016-06-01" ); // Parsing ISO 8601 standard date format.
LocalTime startTime = LocalTime.MIN; // '00:00'.
Both of those classes can be used in factory methods to instantiate LocalDateTime and other classes.
LocalDateTime ldt = LocalDateTime.of( startDate , startTime );
In code above we used LocalTime.MIN to get 00:00. To directly answer your Question, you can also use LocalTime.MAX in the same way to get 23:59:59.999999999. But I do not recommend doing so. Read below about "Half-Open".
Time zone
Time zone is crucial in determining a date and a time. For any given moment the date and the hour-of-day both vary by time zone. A few minutes after midnight in Paris is a new day while still “yesterday” in Montréal.
The Local… types are not actual moments on the timeline. They represent a vague idea about possible moments. As noted above, the first moment of June 1st in Paris is simultaneously May 31st at 6 PM in Montréal. So before performing your database search you need to assign a time zone to your LocalDateTime. Applying a ZoneId produces a ZonedDateTime object.
Perhaps your date-time was intended to be Paris.
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime zdt = ldt.atZone( zoneId );
Or perhaps you intended UTC. This all depends on your business rules, the context in which your app operates. For UTC, we use OffsetDateTime as UTC is not a full time zone but rather a mere offset-from-UTC. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
To get a string as asked for in the Question, extract LocalDate and call toString(). But I do not recommend this as it ignores time zone (read on down below).
String output = odt.toLocalDateTime.toString(); // Not likely to be what you really need.
Best practice in databases is to store the date-time in UTC. I don't know about MongoDB. Be sure to read the doc on how your database driver in Java may be affecting/translating the values you specify.
Start of Day
Be aware that a day does not always start at 00:00:00. In some time zones DST or other anomalies means the day may start at some other time such as 01:00.
The java.time classes will make adjustments as needed in some situations. Be sure to read the class doc so you see if the behavior matches your expectations & needs.
You can ask java.time to find the starting time.
ZonedDateTime zdt = LocalDate.of( "2016-06-01" ).atStartOfDay( zoneId );
Half-Open
Your attempt to determine the end of the day is a problem. That last second is infinitely divisible. Traditional Unix-oriented libraries resolve to whole seconds, the old date-time classes in Java resolve to milliseconds, some databases like Postgres may resolve to microseconds, and java.time and other databases such as H2 resolve to nanoseconds. Do not get in the middle of that.
Generally in date-time programming of a span of time, the best practice is "Half-Open". The beginning of the span is inclusive while the ending is exclusive.
So searching for a month of data in Paris zone means searching for records where the date-time is equal to or later than the start and less than (but not including) the stop.
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
LocalDate startDate = LocalDate.of( "2016-06-01" );
ZonedDateTime zdt start = startDate.atStartOfDay( zoneId );
ZonedDateTime zdt stop = startDate.plusMonths(1).atStartOfDay( zoneId );
// Perform database search where ( ( x >= start ) AND ( x < stop ) ) . Notice '>=' versus '<' with no 'equals' on the latter.
Similarly, the month of records for UTC rather than Paris.
ZoneOffset zoneOffset = ZoneOffset.UTC;
LocalDate startDate = LocalDate.of( "2016-06-01" );
OffsetDateTime start = OffsetDateTime.of( startDate , zoneOffset );
OffsetDateTime stop = OffsetDateTime.plusMonths(1).of( startDate , zoneOffset );
// Perform database search where ( ( x >= start ) AND ( x < stop ) ) . Notice '>=' versus '<' with no 'equals' on the latter.
Using the Half-Open approach consistently throughout your app where handling spans of time will make your code more sensible and easier to understand. You can also train your users to think this way. We all use Half-Open intuitively in situations situations like "Lunch break is from 12:00 to 13:00". We all know this means be back from lunch before the clock strikes 13:00:00.0.
public class DateSample {
public static void main(String[] args) throws ParseException {
String startDate = "2016-06-01";
String endDate = "2016-07-01";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date strDate = formatter.parse(startDate+" 00:00:00.000");
Date enDate = formatter.parse(endDate+" 23:59:59.999");
System.out.println(formatter.format(strDate));
System.out.println(formatter.format(enDate));
}
}
You will get
2016-06-01 00:00:00
2016-07-01 23:59:59
If you are running under jdk 1.8, use LocalDateTime
LocalDateTime is an embedded api of jdk 1.8. You can found explaination here docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html. You can use minus* or plus*, and parse methods
So I tried now for about hours to convert a Timestamp to a local date (CEST).
Date date = new Date(stamp*1000);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CEST"));
String myDate = simpleDateFormat.format(date);
It's not working whatever I tried and looked up in Internet I always get back the UTC time......
for better understanding: stamp is a variable timestamp with type long which I will receive from a service
tl;dr
String output = ZonedDateTime.ofInstant ( Instant.ofEpochSecond ( 1_468_015_200L ) , ZoneId.of ( "Europe/Paris" ) ).toString();
Details
A few issues:
You are not using proper time zone names.
Proper names are in continent/region format.
The 3-4 letter abbreviations so commonly seen in the media such as CEST are not true time zones. Avoid them. They are neither standardized nor unique(!).
You are using old outmoded date-time classes that are poorly designed and confusing. They have been supplanted by the java.time framework.
If by CEST you meant 2 hours ahead of UTC in the summer, then let's take Europe/Paris as an example time zone. Your Question lacks example data, so I'll make up this example.
Apparently your input is a count of whole seconds from the epoch of first moment of 1970 in UTC. That value can be used directly, no need to multiply.
The ZoneId class represents the time zone. An Instant is a point on the timeline in UTC with a resolution up to nanoseconds. A ZonedDateTime is the Instant adjusted into the ZoneId.
ZoneId zoneId = ZoneId.of ( "Europe/Paris" );
long input = 1_468_015_200L; // Whole seconds since start of 1970.
Instant instant = Instant.ofEpochSecond ( input );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
Dump to console.
System.out.println ( "input: " + input + " | instant: " + instant + " | zdt: " + zdt );
input: 1468015200 | instant: 2016-07-08T22:00:00Z | zdt: 2016-07-09T00:00+02:00[Europe/Paris]
Your TimeZone id is likely to be incorrect (well, not recognized by Java). It seems that instead of throwing an exception the TimeZone is evaluated to UTC in that case.
Try this instead:
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("ECT"));
Here is a page giving some information about Java's TimeZone and a list of timezone ids.