Issue
I wanted the date in GMT as String like the javascript code below:
const date = new Date();
date.toGMTString();
I am referring to: Parsing Java String into GMT Date and my code looks like below but this errors out:
private static String getDateGMT() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(date));
return sdf.format(sdf);
}
How do I get the Date in "Thu, 04 Nov 2021 06:50:37 GMT" format?
Solution
java.time and DateTimeFormatter.RFC_1123_DATE_TIME
private static String getDateGMT() {
return OffsetDateTime.now(ZoneId.of("Etc/GMT"))
.format(DateTimeFormatter.RFC_1123_DATE_TIME);
}
This just returned:
Thu, 4 Nov 2021 08:31:33 GMT
Your desired format is built in, so no need to write your own format pattern string. This is good because writing a correct format pattern is always error-prone.
I recommend that you use java.time, the modern Java date and time API, for all of your date and time work.
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
Answered By - Ole V.V.