0

I follow this api document, this api need a Date header, they said they only support GMT date format, so I tried all bellow, but no one success.

@Test
public void testFormat(){
    Date a = new Date("Tue, 08 Dec 2015 06:13:40 GMT");
    System.out.println(a);
    Date b = new Date("Thu, 17 Mar 2012 18:49:58 GMT");
    System.out.println(b);
    System.out.println(b.toGMTString()); // 17 Mar 2012 18:49:58 GMT
    System.out.println(b.toLocaleString());// 2012-3-18 2:49:58
    System.out.println(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(b));//2012-03-18T02:49:58+08:00
}

So, what's the format like this Tue, 08 Dec 2015 06:13:40 GMT, how can I get this format in Java ?

EDIT

Output

Tue Dec 08 14:13:40 CST 2015
Sun Mar 18 02:49:58 CST 2012
17 Mar 2012 18:49:58 GMT
2012-3-18 2:49:58
2012-03-18T02:49:58+08:00

I'm not just asking the pattern, I was wondering is there any standard or name for this format ?

wener
  • 7,191
  • 6
  • 54
  • 78

2 Answers2

4

What's the format like this Tue, 08 Dec 2015 06:13:40 GMT? Is there any standard or name for it?

The doc of Date.parse() refers to it as “the IETF standard date syntax”. That of DateTimeFormatter.RFC_1123_DATE_TIME as “RFC 1123 / RFC 822”. The latter is a lot newer so probably more current.

How can I get this format in Java?

It is built-in as java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME. For example, on my computer OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) just produced

Thu, 6 Apr 2017 15:25:44 +0200

The classes I use are in the java.time package. They are built in with the Java 8 I am using. On Android you can get the java.time classes in the ThreeTenABP.

The zone offset in the above output was +0200. What if I want it to be GMT? Just use OffsetDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.RFC_1123_DATE_TIME), and it will be. More generally, make sure your OffsetDateTime is in the UTC offset. Alternatively, use DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC); this will override the zone of your OffsetDateTime.

If you don’t want a dependency on ThreeTenABP, I believe Zaki Pathan’s comment gives you the solution for Android.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

You should use SimpleDateFormat class. Pass the correct pattern and you can get any output you want to be honest. There is documentation for the function you should refer to Java Doc Simple Date Format

Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
NashPL
  • 461
  • 1
  • 4
  • 19