Reputation: 1037
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?
Upvotes: 0
Views: 957
Reputation: 23
private static String getDateGMT() {
String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z";
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(new Date(System.currentTimeMillis()));
}
Upvotes: 0
Reputation: 86296
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.
Oracle tutorial: Date Time explaining how to use java.time.
Upvotes: 5
Reputation: 1037
private static String getDateGMT() {
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(new Date());
}
Upvotes: 0