-1

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.

Vivo
  • 768
  • 1
  • 8
  • 20

2 Answers2

2

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());

Chris
  • 240
  • 1
  • 8
  • The format asked for is RFC 1123 (see the other answer), and possibly GMT was part of the requirement, at least RFC 1123 supports very few time zone abbreviations. So I expected `Sun, 9 May 2021 14:46:59 GMT`. Instead from your code I got `Sun 9 May 2021 16:47:0 CEST`, CEST is not a supported time zone abbreviation according to RFC 1123. Also 0 seconds should probably be written `00`, not just `0`. – Ole V.V. May 09 '21 at 14:49
1

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110