Reputation: 115
I am looking to understand why this code is giving me different results.
I want to format 2022-10-12T00:00:00.000Z
into yyyy-MM-dd
format.
2022-10-12
2022-10-11
String date = "2022-10-12T00:00:00.000Z";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
TemporalAccessor ta = DateTimeFormatter.ISO_INSTANT.parse(date);
Instant i = Instant.from(ta);
Date d = Date.from(i);
dateFormat.format(d);
Upvotes: 0
Views: 843
Reputation: 79075
The answer by Louis Wasserman is correct. A couple of important points:
SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.SimpleDateFormat
does not have a way to specify a time-zone in the pattern. The way to specify a time-zone with SimpleDateFormat
is by calling SimpleDateFormat#setTimeZone(java.util.TimeZone)
. Without setting time-zone explicitly, SimpleDateFormat
uses the system time-zone. You could get the desired result had you done the following dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
dateFormat.format(d);
I want to format 2022-10-12T00:00:00.000Z into yyyy-MM-dd format
Demo with java.time API:
Since your date-time string is in UTC and you want to get just date part from the UTC date-time:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strDate = "2022-10-12T00:00:00.000Z";
// Parse the given text into an OffsetDateTime and format it
String desiredString = OffsetDateTime.parse(strDate)
.format(DateTimeFormatter.ISO_LOCAL_DATE);
System.out.println(desiredString);
}
}
Output:
2022-10-12
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 4
Reputation: 11
It may be that Date
/SimpleDateFormat
don’t support time zone.
You can try using the java.time package:
LocalDate.now()
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now())
Upvotes: 0
Reputation: 198103
If the online IDE is running in a different time zone than you, it might be 10-12 in one time zone and still 10-11 in another. You have specified Z as the time zone of the input, but you have not specified the time zone used in formatting the date.
Upvotes: 2