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.
- Result when I run it online in Java IDE:
2022-10-12
- But on my own computer the result is:
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);
CodePudding user response:
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.
CodePudding user response:
A couple of important points:
- The java.util date-time API and their formatting API,
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 withSimpleDateFormat
is by callingSimpleDateFormat#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);
Demo with java.time API:
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.
CodePudding user response:
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())