correct date format i am looking for:- "2017-07-06T18:03:39.195+0530"
how to get the +0530 for the current date in java ?
when i am using SimpleDateFormat it is giving +0000 , while it should give +0530 .
=================================================
i have tried using below :-
SimpleDateFormat format = new SimpleDateFormat("enter code hereyyy-MM-dd HH:mm:ss.SSS Z");
String dateString = format.format(new Date());
System.out.println("value of dateString is :"+dateString);
the above code will output :-
value of dateString is :2017-07-10 06:51:27.250 +0000
while it should output : +0530
can you please tell me how can i get the +0530 offset for the above date or current date ?
tl;dr
ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString()
OffsetDateTime
To directly address the Question, use the modern OffsetDateTime class.
OffsetDateTime.now().toString()
See this code run live at IdeOne.com.
odt.toString(): 2019-08-22T17:44:00.219684Z
That will generate a string representing the current moment in the offset used by the JVM’s current default time zone using standard ISO 8601 format. One difference: This method will include the optional COLON : character between hours and minutes of the offset. I suggest never omitting that character as I have seen multiple libraries break on such input, expecting the COLON to be there.
When capturing the current moment, the result may resolve to microseconds. If you prefer milliseconds, truncate, lopping off the micros.
OffsetDateTime.now().truncatedTo( ChronoUnit.MILLIS )
odtTruncated.toString(): 2019-08-22T17:44:00.219Z
That code running at IdeOne.com is in a JVM where the offset is set to zero, for UTC itself. So we see a Z at the end, a common and standard alternative to +00:00, pronounced “Zulu”.
You may want to specify your offset explicitly.
Instant instant = Instant.now() ; // Current moment in UTC.
ZoneOffset offset = ZoneId.of( "Asia/Kolkata" ).getRules().getOffset( instant ) ; // We must pass a moment. India is currently at five and a half hours ahead of UTC. But it has not always been so in the past, and may not always be so in the future.
OffsetDateTime odt = instant.atOffset( offset ) ;
odt.toString(): 2019-08-22T23:00:06.925139+05:30
I think a cleaner syntax is to use ZonedDateTime.
String output = ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString() ;
2019-08-22T23:03:19.072681+05:30
ZonedDateTime
More likely you should be getting the current moment in a time zone rather than a mere offset. If so, see the Answer by RaT.
Be clear on the difference between offset and zone:
An offset-from-UTC is merely a number of hours-minutes-seconds ahead of UTC or behind UTC.
A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region. A zone has a name in Continent/Region format, such as America/Montreal or Africa/Tunis.
Converting
Normally, you should avoid using the terrible date-time classes such as java.util.Date and SimpleDateFormat that are now legacy. Always use Instant, OffsetDateTime, and ZonedDateTime. Never use Date & Calendar.
But if you must you must use the legacy classes when interoperating with old code not yet updated for the java.time classes, you can convert back-and-forth. This is shown in the Answer by RaT.
You can Use Java 8 DateTime API for another solution
ZoneId zone = ZoneId.systemDefault(); //It will give current System's timezone (IST for you)
Date date = new Date(); // Any date
DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS Z", Locale.ENGLISH);
ZonedDateTime zonedTime = ZonedDateTime.ofInstant(date.toInstant(), zone);
System.out.println(zonedTime.format(formatter));
Above code will give you Date with correct Zone Offset
After a lot of searching I found that the timezone problem can be solved with Joda time API. You can use below code to achieve what I want in my question:
DateTime dateTime = DateTime.now();
System.out.println(dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
It outputs the current date with proper timezone:
2017-07-10T15:01:48.319+0530
Set the timezone you need. Your code would looke like:
SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS Z");
format.setTimeZone(TimeZone.getTimeZone("IST"));
String dateString = format.format(new Date());
System.out.println("value of dateString is :"+dateString);
Related
Hi I want to convert String value 2020-12-16T19:20:30+01:00 UTC to either LocalDateTime or ZonedDateTime in java
I tried solution:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-DDThh:mm:ssTZD", Locale.ENGLISH);
final String responseTimeStamp = "2020-12-16T19:20:30+01:00 UTC";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
Which gives me the error
Exception in thread "main" java.lang.IllegalArgumentException: Unknown pattern letter: T at java.base/java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1815) at java.base/java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1712) at java.base/java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:588) at learning/learning.SpringDemo.main(SpringDemo.java:21)
tl;dr
OffsetDateTime
.parse(
"2020-12-16T19:20:30+01:00 UTC"
.replace( " UTC" , "" )
)
.withZoneSameInstant(
ZoneId.of( "America/Edmonton" )
)
ISO 8601
Your input string:
2020-12-16T19:20:30+01:00 UTC
… nearly complies with the ISO 8601 standard for data-exchange date-time formats. To fully comply, delete the SPACE and UTC from the end. The +01:00 at the end means “one hour ahead of UTC", so the UTC at the end is redundant.
String input = "2020-12-16T19:20:30+01:00 UTC".replace( " UTC" , "" ) ;
Offset versus time zone
Parse as an OffsetDateTime because your input indicates small offset from UTC, not a time zone.
An offset is merely a number of hours-minutes-seconds ahead/behind the prime meridian of 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 as decided by their politicians. A time zone has a name in format of Continent/Region, such as Europe/Paris and Africa/Tunis.
OffsetDateTime
So the other Answer’s suggestion to use ZonedDateTime for parsing is misguided as no time zone is indicated. Your input has only an offset, therefore use OffsetDateTime.
No need to specify a formatting pattern. Our modified input complies with ISO 8601, and the java.time classes use those standard formats by default when parsing/generating strings.
OffsetDateTime odt = OffsetDateTime.parse( input ) ;
LocalDateTime
You asked how to get a LocalDateTime. That class lacks any concept of offset or time zone. So beware, if you convert from OffsetDateTime, you are discarding valuable information.
So while I don’t recommend doing this, here is the code.
LocalDateTime ldt = odt.toLocalDateTime() ;
ZonedDateTime
You asked how to adjust into a time zone.
To adjust from our offset to a time zone, merely specify the desired time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.withZoneSameInstant( z ) ;
There are a few things wrong with your code. I suggest you to take a look at the DateTimeFormatter documentation.
YYYY -> This means week-based-year, you can have a look here to see the difference between year-of-era. So you should be using yyyy.
DD -> This means day-of-year, so December 16 is equal to 350. In your case you want to use dd, day-of-month.
T -> There isn't a pattern for T, so you can put it like a text to formmat you date 'T'
TZD -> I don't know what you are trying to use here and I couldn't find the patter +03:00 UTC, you can try to use O
So your final pattern should be "yyyy-MM-dd'T'HH:mm:ssO". It doens't work for UTC and I couldn't find it on ZoneId list, maybe because UTC is +00:00 already, so UTC+01:00 is equal to +01:00.
After a lot of working understanding the pattern, I found out that you are looking for ISO_ZONED_DATE_TIME, so you could just change your code like below:
DateTimeFormatter dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME;
final String responseTimeStamp = "2020-12-16T19:20:30+01:00";
ZonedDateTime zdt = ZonedDateTime.parse(responseTimeStamp, dtf);
I'm creating a string out from current time and I wanted to convert it to timestamp again, but the thing is, that it's subtracts 2 hours while converting.
This is the steps I'm doing -
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("uuuu-MM-dd")).appendLiteral(" ")
.append(DateTimeFormatter.ofPattern("HH:mm:ss")).parseLenient();
long ts = Clock.systemUTC().millis();
System.out.println(ts);
Instant instant = Instant.ofEpochMilli(ts);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
long timestamp = simpleDateFormat.parse(str).getTime();
System.out.println(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
output -
1639065502667
1639058302000
(2021-12-09 15:58:22
2021-12-09 13:58:22)
why is the diff of the 2 hours?
how can I parse it so that the outputs will be equal?
tl;dr
Trying to understand Date, Calendar, and SimpleDateFormat is a huge waste of time. Use only their replacements, the java.time classes.
LocalDateTime // Represent a date with time-of-day, but lacking the context of a time zone or offset-from-UTC. So *not* a moment, *not* a point on the timeline.
.parse( // Parse your text string input into a date-time object.
"2021-12-09 15:58:22" // Your input of date with time-of-day but no offset/zone.
.replace( " " , "T" ) // Replace SPACE with a `T` to comply with standard ISO 8601 format.
) // Returns a `LocalDateTime` object.
.atZone( // Place that date-with-time into the context a particular time zone.
ZoneId.of( "America/Montreal" ) // Specify a time zone by its `Continent/Region` name.
) // Returns a `ZonedDateTime` object, a date with time-of-day as seen through the wall-clock time used by the people of a particular region. This *does* represent a moment, *is* a specific point on the timeline.
.toInstant() // Adjust from time zone to UTC (an offset of zero hours-minutes-seconds). This represents the very same moment as the `ZonedDateTime` object above, but as seen through a different wall-clock time.
.toEpochMilli() // Get a count of milliseconds from first moment of 1970 in UTC (1970-01-01T00:00Z) to the moment of our `Instant` object (& `ZonedDateTime` object).
See this code run live at IdeOne.com. There you can click fork to make a copy, alter, and run.
1639083502000
Avoid legacy date-time classes
Regarding your specific question about a two hour difference, the obvious cause would be a time zone difference.
Parsing incomplete information
Your parsing, SimpleDateFormat("yyyy-MM-dd HH:mm:ss") is something of a wild card. The result will be a java.util.Date object, which represents a moment, a date with time-of-day as seen with an offset of zero. But your input lacks an indicator of offset or zone. As commented by Sotirios Delimanolis, you are parsing with partial input, with incomplete information.
So some default zone/offset will be applied. I do not know what zone or offset in particular, because I do not care. That terrible class is tragically flawed, and should be avoided.
Also, yet another problem with the Date class is that its toString method has the anti-feature of applying the JVM’s current default time zone to adjust away from the UTC value represented by that class. Very confusing, as this creates the illusion of that zone being a part of Date object but it is not. As I said, a terrible class, tragically flawed.
Use only java.time classes instead.
java.time
Understand that a date with time-of-day is inherently ambiguous, is not a moment.
If you are tracking 4 PM on the 9th, we do not know if that means 4 PM in Tokyo Japan, 4 PM in Toulouse France, or 4 PM in Toledo Ohio US — three very different moments that happen several hours apart.
LocalDateTime ldt = LocalDateTime.parse( "2021-12-09 16:00:00" ) ;
To track a moment, a point on the timeline, you must place ne date-with-time in the context of an offset from UTC or of a time zone.
An offset is merely a number of hours-minutes-seconds ahead or behind the baseline of modern timekeeping, the prime meridian at Royal Observatory, Greenwich.
A time zone is much more. A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region. Each zone has a name in format of Continent/Region such as Europe/Berlin or Asia/Tokyo.
To track moments as seen in UTC, with an offset of zero, use Instant.
Instant instant = Instant.now() ;
To see that same moment through the wall-clock time used by people in a region, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
As for your use of SimpleDateFormat, Date, and Calendar, don’t. Avoid these legacy date-time classes. Hey were designed by people who did not understand date-time handling. They were supplanted years ago by the modern java.time classes defined in JSR 310. Sun, Oracle, and the JCP community all gave up on those classes. I suggest you do the same.
In your code:
long ts = Clock.systemUTC().millis();
Instant instant = Instant.ofEpochMilli(ts);
That is the same as doing this:
Instant.now().truncatedTo( ChronoUnit.MILLISECONDS )
In your code:
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
(A) When working with mere offsets rather than time zones, use OffsetDateTime class. The ZonedDateTime class is for working with time zones.
(B) A briefer way to adjust from Instant to a zoned moment was shown above:
myInstant.atZone( z )
The answer was only setting the timezone to UTC -
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder().append(DateTimeFormatter.ofPattern("uuuu-MM-dd")).appendLiteral(" ")
.append(DateTimeFormatter.ofPattern("HH:mm:ss")).parseLenient();
long ts = Clock.systemUTC().millis();
System.out.println(ts);
Instant instant = Instant.ofEpochMilli(ts);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneOffset.UTC);
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
*******
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
*******
long timestamp = simpleDateFormat.parse(str).getTime();
System.out.println(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
The dateTimeFomatter builder uses format without milliseconds and without timezone.
That's why the str value contain no information about them.
Then simpleDateFormat.parse(str) uses timezone of JVM which is UTC+02:00 in this case.
Trace what is going on:
Instant instant = Instant.now();
// => 2021-12-09 15:58:22.798 +00:00
String str = zonedDateTime.format(dateTimeFormatterBuilder.toFormatter());
// => "2021-12-09 15:58:22"
simpleDateFormat.parse(str);
// => 2021-12-09 15:58:22.000 +02:00
You just need to fix the pattern (add millis .SSS and timezone XXX parts) to make the results consistent as expected:
DateTimeFormatter.ofPattern("HH:mm:ss.SSSXXX")
// and something similar for SimpleDateFormat if needed
Parsing Instant from a custom formatted string.
This example shows how to parse Instant from serialized time assuming that there is a fixed timezone for all cases.
var serializedDateTime = "2020-01-01 10:20:30";
var zoneId = ZoneOffset.UTC; // may be any other zone
var format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
var instant = LocalDateTime
.parse(serializedDateTime, format)
// LocalDateTime is unzoned, just representation of (date + time) numbers in a single object
.atZone(zoneId)
// apply a zone to get ZonedDateTime (point in space-time on Earth)
.toInstant();
// convert to Instant (the same point adjusted to UTC+00:00)
Let me guess, your timezone is UTC+2?
simpleDateFormat.parse(str) assume that your date in current system timezone, but it is in UTC.
DateTimes in different formats is always a problem for me. I have a date with the datatype string like "2021-07-25"
I want to convert this date to the datatype LocalDateTime in the format 2021-07-25T00:00:00.000-05:00. I have the get and set property like below
private LocalDateTime relationshipStatusDate;
public LocalDateTime getRelationshipStatusDate() {
return relationshipStatusDate;
}
public void setRelationshipStatusDate(LocalDateTime relationshipStatusDate) {
this.relationshipStatusDate = relationshipStatusDate;
}
public void setRelationshipStatusDate(String time) {
if (time != null) {
try {
long epochTime = Long.parseLong(time);
this.relationshipStatusDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochTime), ZoneOffset.UTC);
} catch (NumberFormatException e){
this.relationshipStatusDate = LocalDateTime.parse(time, DateTimeFormatter.ISO_DATE_TIME);
}
}
}
and I am trying to format like below and its failing with an error "Unknown pattern letter T"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-ddT00:00:00.000-05:00");
LocalDateTime dateTime = LocalDateTime.parse(statusDate, formatter);
Your format won't be parsable as it doesn't support default values like T00:00:00.000-05:00. You could escape literals e.g. use 'T00:00...' but that would just make the parser ignore them.
Instead, if all you get is a date then only parse a date and add the default time after that, e.g. like this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
LocalDate date = LocalDate.parse(statusDate, formatter );
LocalDateTime dateTime = date.atStartOfDay(); //"relative" representation as the absolute instant would require adding a timezone
ZonedDateTime zonedDT = date.atSTartOfDay(ZoneOffset.UTC); //"absolute" representation of instant
I want to convert this date to the datatype LocalDateTime in the format 2021-07-25T00:00:00.000-05:00.
Note the potential misconception here: LocalDateTime does NOT have a format. It represents a date and time (from a local point of reference - not in absolute terms as the timezone is missing) and provides access to individual fields such as day of month, day of week etc. but it is not formatted. Formatting is applied when you convert that date object to a string.
tl;dr
LocalDate // Represent a date-only value, without a time-of-day and without a time zone or offset-from-UTC.
.parse( "2021-07-25" ) // Parse a string in standard ISO 8601 format to instantiate a `LocalDate` object.
.atStartOfDay( // Determine the first moment of the day on that date in that zone. NB: The day does *not* always begin at 00:00, so never assume that time.
ZoneId.of( "America/Bogota" ) // Real time zones have a name in Continent/Region format. Never use 2-4 letter pseudo-zones such as `CST` or `IST`.
) // Returns a `ZonedDateTime` object, a moment in the context of a time zone.
.toOffsetDateTime() // Strips away the time zone information, leaving only a date with time-of-day in a particular offset. Returns an `OffsetDateTime` object.
.toString() // Generate text in standard ISO 8601 format.
2021-07-25T00:00-05:00
Details
LocalDateTime is the wrong class
You said:
datatype LocalDateTime in the format 2021-07-25T00:00:00.000-05:00
That is a contradiction. The -05:00 at the end of your string is an offset-from-UTC. A LocalDateTime object has no offset.
You seem to misunderstand the purpose of LocalDateTime. That class does not represent a moment as seen through the wall-clock time with an offset-from-UTC used by the people of a particular region. For that purpose, use OffsetDateTime, or preferably, ZonedDateTime.
Use documentation rather than intuition when programming with unfamiliar classes. To quote the Javadoc for LocalDateTime:
A date-time without a time-zone … such as 2007-12-03T10:15:30.
…
This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, … It cannot represent an instant on the time-line …
Here is my chart to summarize the types. Three classes represent a moment, while LocalDateTime does not.
You said:
I have a date with the datatype string like "2021-07-25"
So use LocalDate to represent that value.
By default, the java.time classes use standard ISO 8601 format when parsing/generating text. So no need to specify a formatting pattern here, as your input complies with that standard.
LocalDate ld = LocalDate.parse( "2021-07-25" ) ;
You said:
I want to convert this date to … the format 2021-07-25T00:00:00.000-05:00
Your example there uses only a mere offset rather than a time zone. I suggest you use a time zone whenever possible.
An offset is simply a number of hours-minutes-seconds, nothing more. A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by people of a particular region, as decided by their politicians.
ZoneId
So specify your time zone using Continent/Region naming.
ZoneId z = ZoneId.of( "America/Cancun" );
ZonedDateTime
Let java.time determine the first moment of the day on that date as seen in that time zone. Be aware that the day does not always start at 00:00. So never hard-code that time-of-day; let java.time do the work here.
ZonedDateTime zdt = ld.atStartOfDay( z ); // Determine the first moment of the day as seen in that zone. Not always 00:00.
Generate text to represent the value inside our ZonedDateTime. The ZonedDateTime#toString method generates text in a format that wisely extends the ISO 8601 format by appending the name of the time zone in square brackets.
String output = zdt.toString();
2021-07-25T00:00-05:00[America/Cancun]
Pull all that code together.
LocalDate ld = LocalDate.parse( "2021-07-25" );
ZoneId z = ZoneId.of( "America/Cancun" );
ZonedDateTime zdt = ld.atStartOfDay( z ); // Determine the first moment of the day as seen in that zone. Not always 00:00.
String output = zdt.toString();
See this code run live at IdeOne.com.
2021-07-25T00:00-05:00[America/Cancun]
OffsetDateTime
If you insist on generating text in your stated format, while omitting the name of the time zone, use OffsetDateTime.
String output = zdt.toOffSetDateTime().toString() ;
All of these topics have been covered many times on Stack Overflow. Search to learn more.
I am trying to parse an input string to local date time.
Below is my piece of code
ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z", MY_DATE_TIME_FORMATTER);
where
MY_DATE_TIME_FORMATTER= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.appendLiteral('T')
.append(ISO_LOCAL_TIME)
.appendLiteral('Z')
.appendOffset("+HH:mm", "+0000")
.toFormatter();
I get the following exception
java.time.format.DateTimeParseException: Text '2019-11-26T19:30:00Z' could not be parsed at index 19
Can you please advise on what I am doing wrong here?
Instant.parse
No formatting pattern needed.
Instant.parse( "2019-11-26T19:30:00Z" )
Your input format complies with ISO 8601 standard. That particular format has a Z on the end. That letter means UTC (an offset of zero hours-minutes-seconds), and is pronounced “Zulu”.
The Instant class in java.time represents a moment in UTC, always UTC.
Using ZonedDateTime class for that input is not the most appropriate. We have:
Instant for values that are always in UTC.
OffsetDateTime for moments where only an offset-from-UTC is known but not a time zone. Use this class for UTC values too when you need more flexibility such as generating strings in various formats. `instant.atOffset(
ZonedDateTime for values in a time zone. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.
To view that same moment adjusted to the offset used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime object.
Instant instant = Instant.parse( "2019-11-26T19:30:00Z" ) ; // Default format for parsing a moment in UTC.
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, same point on the timeline, different wall-clock time.
See this code run live at IdeOne.com.
instant.toString(): 2019-11-26T19:30:00Z
zdt.toString(): 2019-11-26T12:30-07:00[America/Edmonton]
Add
.appendZoneOrOffsetId()
instead of these two lines:
.appendLiteral('Z')
.appendOffset("+HH:mm", "+0000")
The whole builder example:
MY_DATE_TIME_FORMATTER= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(ISO_LOCAL_DATE)
.appendLiteral('T')
.append(ISO_LOCAL_TIME)
.appendZoneOrOffsetId()
.toFormatter();
P.S. In your specific case I'd rather use the standard ISO formatter (as Hristo mentioned):
ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z", DateTimeFormatter.ISO_ZONED_DATE_TIME);
Moreover, the ZonedDateTime::parse method will work even without the explicit formatter. Since it's used by default:
ZonedDateTime z = ZonedDateTime.parse("2019-11-26T19:30:00Z");
Use the built in ISO zoned time formatter
ZonedDateTime.parse("2019-11-26T19:30:00Z", DateTimeFormatter.ISO_ZONED_DATE_TIME);
As per the requirement, my code is supposed to append date from a ZonedDateTime parameter, and Time from OffSetTime parameter into this format, "yyyy-MM-dd HH:mm:ss.SSSz". However, i was not been able to achieve this
I have tried various ways , including the one below, using DateTimeFormatter.
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-05-23T09:00:00-05:00");
OffsetTime offsetTime = OffsetTime.parse("08:59:00-05:00");
LocalDateTime localDateTime = LocalDateTime.of(zonedDateTime.toLocalDate(), offsetTime.toLocalTime());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSz");
String finalDate = localDateTime.format(formatter);
I notice that :
- code is throwing "java.time.DateTimeException: Unable to extract value: class java.time.LocalDateTime" at localDateTime.format(formatter)
The expectation is to get the DateTime in String like so - "2019-05-23T08:59:00.000Z"
Any help appreciated, Thank you for your time.
Four issues:
LocalDateTime doesn't have any time zone information, so don't use it.
Even if it did, your inputs only have a time zone offset, not a full time zone, so you format string cannot use z, as that requires a time zone name. Use XXX instead.
Since the inputs are offset -05:00 you shouldn't expect output with Z (Zulu), as that means +00:00, unless you also expect the time to be adjusted by 5 hours.
The format pattern for year should use uuuu, not yyyy. See uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Assuming you want to keep the time zone, change code to:
ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-05-23T09:00:00-05:00");
OffsetTime offsetTime = OffsetTime.parse("08:59:00-05:00");
OffsetDateTime offsetDateTime = zonedDateTime.toLocalDate().atTime(offsetTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSXXX");
System.out.println(offsetDateTime.format(formatter));
2019-05-23 08:59:00.000-05:00
If you instead want Zulu time, i.e. UTC, with the time adjusted, add the line to make the adjustment:
OffsetDateTime offsetDateTime = zonedDateTime.toLocalDate().atTime(offsetTime)
.withOffsetSameInstant(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSSXXX");
System.out.println(offsetDateTime.format(formatter));
2019-05-23 13:59:00.000Z