Aavik
Aavik

Reputation: 1037

Get Date in GMT format as String

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

Answers (3)

libao zhou
libao zhou

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

Anonymous
Anonymous

Reputation: 86296

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.

Upvotes: 5

Aavik
Aavik

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

Related Questions