Reputation: 1868
If I want my formatted date to look like:
2021-07-21 2:02:08.483 p.m. EDT
Can the SimpleDateFormat
class print "EDT" or "EST", without me hard-coding it? What would be the format specifier? So far I have:
yyyy-MM-dd HH:mm:ss.SSS a
Upvotes: 1
Views: 129
Reputation: 79095
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:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd H:mm:ss a zzz", Locale.CANADA);
String strDateTime = ZonedDateTime.now(ZoneId.of("America/New_York")).format(dtf);
System.out.println(strDateTime);
}
}
Output:
2021-07-21 10:34:12 a.m. EDT
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness, given below is the solution using SimpleDateFormat
.
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss a zzz", Locale.CANADA);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateTime = sdf.format(new Date());
System.out.println(strDateTime);
}
}
Output:
2021-07-21 10:36:52 a.m. EDT
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. 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 and How to use ThreeTenABP in Android Project.
Upvotes: 6
Reputation: 6732
You just need to add a z
to your pattern - but next time, refer to the docs.
Upvotes: 0