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:
- For the first format, you can build the required
DateTimeFormatter
using the DateTimeFormatterBuilder
.
- For the second pattern, you can simply use
DateTimeFormatter
with the required pattern letters.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter dtf1 =
new DateTimeFormatterBuilder()
.appendPattern("MMMM dd, uuuu 'at' h:mm:ss a 'UTC'")
.appendOffset("+H:mm", "Z")
.toFormatter(Locale.ENGLISH);
System.out.println(now.format(dtf1));
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
System.out.println(now.format(dtf2));
}
}
Output:
September 15, 2021 at 10:22:43 PM UTC+5:30
Wed Sep 15 22:22:43 GMT+05:30 2021
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* 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.