Get current date time in the desired format

934 Views Asked by At

I would like to get the current date time in the following format

Tue, 20 Aug 2014 22:51:31 GMT

But I am finding it hard to get it to the format specifier e.g ddmmyy like that My doubt is what to specify Tue in symbolically like wise how to specify GMT symbolically.

2

There are 2 best solutions below

1
On BEST ANSWER

Look into using a SimpleDateFormat.

Edit:

It looks like you might want the format string "E d MMM y H:m:s z".

SimpleDateFormat format = new SimpleDateFormat("E d MMM y H:m:s z", Locale.US); String date = format.format(new Date());

1
On

java.time

I recommend you use the modern date-time API*.

Your desired format is available out-of-the-box as DateTimeFormatter.RFC_1123_DATE_TIME.

Demo:

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME);
        System.out.println(strDateTime);
    }
}

Output:

Sun, 9 May 2021 14:36:28 GMT

Learn more about the 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.