2

I will work with third party API. They accept a date pattern like:

2012-02-15T17:34:37.937-0600

I know the pattern should be match like

yyyy-MM-ddTHH:mm:ss.s

But I am not sure how to represent the last "-0600" timezone? I think the standard timezone is "-06:00", anyone knows how to get rid of the ":" in the date pattern?

Thanks.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
ttt
  • 3,934
  • 8
  • 46
  • 85

3 Answers3

6

maybe you want "Z" ?

see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html:

  • 'z' gives you "Pacific Standard Time; PST; GMT-08:00"
  • 'Z' gives you "-0800"

This code:

final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ");

produces:

2012-05-11T12:21:57.598+1000

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
ianpojman
  • 1,743
  • 1
  • 15
  • 20
  • @ttt: Note also the uppercase 'S' for milliseconds (differs from your question's datespec) and the single quotes around 'T'. – Greg Kopff May 11 '12 at 02:25
1

java.text.SimpleDateFormat should be very helpful for customize the string representation:

Z Time zone RFC 822 time zone -0800

James Gan
  • 6,988
  • 4
  • 28
  • 36
0

I know the pattern should be match like

yyyy-MM-ddTHH:mm:ss.s

No, there are two problems in this pattern:

  1. The symbol for fraction-of-second is S, but you have used s.
  2. The ZoneOffset specifier, Z is missing in the pattern.

java.time

The accepted answer uses SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern Date-Time API. Since then, it is highly recommended to stop using the legacy date-time API.

Demo using the modern date-time API:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH);
        System.out.println(OffsetDateTime.now(ZoneOffset.of("-06:00")).format(dtf));
    }
}

Output:

2022-12-28T13:21:05.459-0600

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

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