12

One of the external APIs we use requires

"YYYY-MM-DDThh:mm:ssTZD"

format to be passed in

XMLGregorianCalendar

object. I am not sure if there is anything in Java that supports "T". I was wondering, if a date can be parsed into above format in Java? An example of a valid date they have provided is

"2009-07-16T19:20:30-05:00"............

 Update:

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ");        
        GregorianCalendar gc = new GregorianCalendar();
        String dateString = sdf.format(gc.getTime());       
        gc.setTime(sdf.parse(dateString));      
        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);

Output:

2014-04-17T13:11:30.000+01:00

Abidi
  • 7,846
  • 14
  • 43
  • 65

4 Answers4

25

Use JodaTime's DateTimeFormat API with "yyyy-MM-dd'T'HH:mm:ssZ" date pattern

String date = "2009-07-16T19:20:30-05:00";
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(date);
System.out.println(dateTime); // 2009-07-16T19:20:30-05:00
Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • What if I have pattern like this "yyyy-MM-ddTHH:mm:ssZ" (T without single quotes), Is there any way around to parse this thing to Date object ? – Shamim Ahmad Dec 21 '16 at 07:00
  • @ShamimAhmad, it will throw an exception: `java.lang.IllegalArgumentException: Unknown pattern character 'T'`. – CoolMind Sep 26 '18 at 11:26
8

Try Java 8 LocalDateTime.parse

You could also use threeten if you're on an earlier Java Version.

Example: DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ").format(yourLocalDateTime)

Nicholas DiPiazza
  • 10,029
  • 11
  • 83
  • 152
cbach
  • 394
  • 3
  • 8
7

You need to put it in single quotes.

Try

YYYY-mm-dd'T'hh:MM:ssZ
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
7

Yes,you can.Try this date formatter.

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
mstzn
  • 2,881
  • 3
  • 25
  • 37