I need to generate a new Date();
already with the correct time zone, because I need to record the date and time that a new data is received on my server. (I know that you can use the SimpleDateFormat, but it requires to parse a already created string).
I'm using Java Spring Boot.
CodePudding user response:
java.time
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*.
Solution using java.time
, the modern Date-Time API: You can use ZonedDateTime
with the applicable ZoneId
.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// Use the applicable ZoneId
ZoneId zoneId = ZoneId.of("Asia/Dubai");
ZonedDateTime now = ZonedDateTime.now(zoneId);
System.out.println(now);
}
}
Output from a sample run:
2021-10-30T02:26:07.471319 04:00[Asia/Dubai]
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time
API with JDBC.
A note on java.util.Date
:
A java.util.Date
object simply represents an instant on the timeline — a wrapper around the number of milliseconds since the UNIX epoch (January 1, 1970, 00:00:00 GMT). Since it does not hold any timezone information, its toString
function applies the JVM's timezone to return a String
in the format, EEE MMM dd HH:mm:ss zzz yyyy
, derived from this milliseconds value. To get the String
representation of the java.util.Date
object in a different format and timezone, you need to use SimpleDateFormat
with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time
.
CodePudding user response:
Use DateFormat. For example,
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");