SimpleDateFormat throwing Unparseable exception [duplicate] - java

This question already has answers here:
How to Format ISO-8601 in Java
(3 answers)
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 4 years ago.
I know there are alot of these, but I can'e seem to find the magic string for this date format:
String textDate = "2018-04-25T18:23:57.556Z";
My code is:
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.parse(textDate)
What's weird is there is a "Z" in the date string itself, so I am not sure how the timezone works on this one.
If I change the date format to:
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
It works, but I am not sure how to get the time zone then...

Z = UTC
The literal "Z" is actually part of the ISO 8601 datetime standard for UTC times. When "Z" (Zulu) is tacked on the end of a time, it indicates that that time is UTC, so really the literal Z is part of the time.
The java.time classes use the ISO 8601 standard formats by default when parsing/generating strings. The Instant class represents a moment in UTC, a perfect fit for your input string.
Instant instant = Instant.parse( "2018-04-25T18:23:57.556Z" ) ;

Related

Java 8 : formatting Instant according to ISO 8601 with Zone-Offset [duplicate]

This question already has answers here:
Current date and time in Java
(2 answers)
Why does Java's java.time.format.DateTimeFormatter#format(LocalDateTime) add a year?
(2 answers)
Java, DateTimeFormatter is not considering ZoneDateTime's timezone [duplicate]
(1 answer)
Closed 8 months ago.
I'm trying to create the ISO 8601 formatted DateTime from the Instant object as per the reference in this article I used the format YYYY-MM-DD'T'hh:mm:ss'T'ZD to parse the Instant date as below.
But it's generating the time in wrong format:
2022-06-172T06:08:13T-0500172
The expected format should be:
2022-06-21T13:31:49-05:00
My code:
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("YYYY-MM-DD'T'hh:mm:ss'T'ZD")
.withZone(ZoneId.systemDefault());
formatter.format(Instant.now())
How can I produce the formatted time as shown below?
2022-06-21T13:31:49-05:00
I guess the pattern you need is "yyyy-MM-dd'T'hh:mm:ssxxx"
y - year (not Y - week-based-year);
d - day of the month (not D - day of the year);
x - zone-offset (not ZD);
There's no need in T in the end if you don't want it to be present in the formatted string.
Quote from the documentation regarding the zone-offset formatting:
Offset X and x: This formats the offset based on the number of pattern
letters. One letter outputs just the hour, such as '+01', unless the
minute is non-zero in which case the minute is also output, such as
'+0130'. Two letters outputs the hour and minute, without a colon,
such as '+0130'. Three letters outputs the hour and minute, with a
colon, such as +01:30.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'hh:mm:ssxxx")
.withZone(ZoneId.systemDefault());
System.out.println(formatter.format(Instant.now()));
Output:
2022-06-22T03:05:43+03:00
tl;dr
help with producing the time formatted as 2022-06-21T13:31:49-05:00
OffsetDateTime.now().toString()
2022-06-22T04:38:55.902569200+03:00
ISO 8601
No need to define a formatting pattern.
Your desired output complies with ISO 8601 standard of date-time formats. The java.time classes use these standard formats by default when parsing/generating text.
OffsetDateTime
To represent a moment as seen in a particular offset, use OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.now() ;
Generate your text by calling toString.
String output = odt.toString() ;
2022-06-22T04:38:55.902569200+03:00
If you want to discard the fractional second, truncate.
OffsetDateTime
.now()
.truncatedTo( ChronoUnit.SECONDS )
.toString()
2022-06-22T04:38:55+03:00

how to format String to Date with format dd-mm-yyyy in java [duplicate]

This question already has answers here:
Get Date type object in format in java
(6 answers)
String date convertion to Date Conversion [duplicate]
(1 answer)
display Java.util.Date in a specific format
(11 answers)
Closed 9 months ago.
I need some support. I desired convert a variable String to Date. The variable Date should be format dd-MM-yyyy.
import java.util.Date;
....
...
String a = "2022-05-12";
Date b; // should be dd-MM-yyyy
do some to format...
return b; // return b with format dd-MM-yyyy, remember this variable is type Date no String
I was trying to do something but the format obtained is not the desired one.
tl;dr
LocalDate
.parse( "2022-05-12" )
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
12-05-2022
java.time
Use modern java.time classes. Never use the terrible Date, Calendar, SimpleDateFormat classes.
ISO 8601
Your input conforms to ISO 8601 standard format used by default in the java.time classes for parsing/generating text. So no need to specify a formatting pattern.
LocalDate
Parse your date-only input as a date-only object, a LocalDate.
String input = "2022-05-12" ;
LocalDate ld = LocalDate.parse( input ) ;
To generate text in your desired format, specify a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;
Rather than hardcode a particular pattern, I suggest learning to automatically localize using DateTimeFormatter.ofLocalizedDate.
All this has been covered many many times already on Stack Overflow. Always search thoroughly before posting. Search to learn more.
What you are doing is converting from string to date. It seems that you want it to PRINT the date in a specific format.
Where is an example of how to do it:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2022/05/18 00:18:43

String from ZonedTimeDate to java.util.Date without name of the month and day [duplicate]

This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
How to convert date in to yyyy-MM-dd Format?
(6 answers)
How to convert Java String "EEE MMM dd HH:mm:ss zzz yyyy"date type to Java util.Date "yyyy-MM-dd" [duplicate]
(1 answer)
Closed 1 year ago.
I'm using a ZonedDateTime to get the current date-time. Because I dont want it with the time, I'm making it the format of uuuu-MM-dd and it gives me back a String as 2021-08-23
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu-MM-dd" );
String date_string = zdt.format(formatter);
System.out.println(date_string);//2021-08-23
Now how can I convert this String 2021-08-23 to a java.util.Date? I want the date to look exactly like the String...
This is what I have tried but it won't get me the date looking like the string
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter1.parse(date_string);
Will give me the date in this format: Mon Aug 23 00:00:00 EEST 2021... How can I
convert my string into a date and keep the date looking like the string?
tl;dr
LocalDate.now().toString()
2021-08-23
Better to specify desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).toString()
Details
LocalDate
If you want a date-only, use LocalDate.
LocalDate ld = myZonedDateTime.toLocalDate() ;
The java.time.Date class is terribly flawed, and should be avoided. The class was supplanted years ago by the modern java.time classes defined in JSR 310.
If you must use this class to interoperable with old code not yet updated to java.time, you can convert back and forth between the legacy classes and their replacements. Look for the new conversion methods added to the old classes.
java.util.Date is not a date!
Understand that among its many flaws is the name of java.util.Date. That class represents not a date but a moment in time as seen in UTC. So its replacement is java.time.Instant, not LocalDate.
java.util.Date d = java.util.Date.from( myZonedDateTime.toInstant() );
You asked:
How can I convert my string into a date and keep the date looking like the string?
Understand that none of these date-time classes are text. They have their own internally defined representation of a date-time value, not String.
It sounds like you simply want text in standard ISO 8601 format (YYYY-MM-DD) for a date-only value. The java.time classes use the standard ISO 8601 formats by default when generating/parsing strings. So no need to define a custom formatting pattern.
String output = myZonedDateTime.toLocalDate().toString() ;
Date-time objects have no format, are not text
You asked:
Now how can I convert this String 2021-08-23 to a java.util.Date? I want the date to look exactly like the String
What you request makes no sense.
A java.util.Date object is a date-time object, not text, not String. A java.util.Date object has no “format”.
Likewise, a java.time.ZonedDateTime object is a date-time object, not text, not String. A java.time.ZonedDateTime object has no “format”.
And so too, a java.time.LocalDate object is a date object, not text, not String. A java.time.LocalDate object has no “format”.
These date-time objects have a toString method that generates text representing the embedded value using a default format. But you should not conflate that generated text with the original date-time object.

How to convert UTC timestamp to asia/jakarta time [duplicate]

This question already has answers here:
Convert UTC date to current timezone
(5 answers)
Timezone conversion
(13 answers)
Closed 2 years ago.
I have string timestamp like
2020-05-25 08:03:24
I have tried to split the String using " " (a whitespace) as delimiter to get two Strings "2020-05-25" and "08:03:24". After that, I used substring to get the hours and added 7 to have jakarta time.
But when it is 17:01:00 for example, my calculated date is wrong.
The date given is in UTC.
I want to convert it become timezone [ASIA/Jakarta] how to convert utc timestamp become asia jakarta time?
You can use java.time if you are using Java 8 or higher.
The library provides handy possibilities of converting datetimes that don't have information about a time zone (like your example String) to a zone and handle conversions from one zone to another.
See this example:
public static void main(String[] args) {
// datetime string without a time zone or offset
String utcTimestamp = "2020-05-25 08:03:24";
// parse the datetime as it is to an object that only knows date and time (no zone)
LocalDateTime datetimeWithoutZone = LocalDateTime.parse(utcTimestamp,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// convert it to a zone-aware datetime object by adding a zone
ZonedDateTime utcZdt = datetimeWithoutZone.atZone(ZoneId.of("UTC"));
// print the datetime in utc once
System.out.println(utcZdt);
// then convert the zoned datetime to a different time zone
ZonedDateTime asiaJakartaZdt = utcZdt.withZoneSameInstant(ZoneId.of("Asia/Jakarta"));
// and print the result
System.out.println(asiaJakartaZdt);
}
The output is
2020-05-25T08:03:24Z[UTC]
2020-05-25T15:03:24+07:00[Asia/Jakarta]

Which date time format is this? [duplicate]

This question already has answers here:
SimpleDateFormat parsing date with 'Z' literal [duplicate]
(12 answers)
Closed 6 years ago.
I wonder which format is the following datetime value:
"2016-05-18T12:05:33Z"
This date time format is used on Zendesk's tickets in the fields of created_at and updated_at.
I know that its "yyyy-MM-ddTHH:mm:ss........", but what does the "Z" stand for?
What I want to do is parse and convert into a java.time class for storing dates and times, but I do not know which is the best one.
That is ISO 8601 format and the Z is the timezone indicator; it means UTC.
The best java.time class to use is ZonedDateTime. Example:
ZonedDateTime dateTime = ZonedDateTime.parse("2016-05-18T12:05:33Z",
DateTimeFormatter.ISO_DATE_TIME);

Categories

Resources