1

I am developing a java sample in which date is in string like - 2016-07-19T16:54:03.000+05:30. I want to convert it to DateTime object.How can I do it in java? I have tried this code -

DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS+Z").parseDateTime("2016-07-19T16:54:03.000+05:30")

It give java.lang.IllegalArgumentException: Invalid format: "2016-07-19T16:54:03.000+05:30" is malformed at "05:30" exception.

parita porwal
  • 662
  • 1
  • 10
  • 32

3 Answers3

1

You could use SimpleDateFormat:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Main {
  public static void main(String[] args) {
    try {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
      Date parsed = format.parse("2016-07-19T16:54:03.000+05:30");
      System.out.println(parsed);
    } catch (ParseException e){
      e.printStackTrace();
    }
  }
}

Output:

Tue Jul 19 11:54:03 UTC 2016

Try it here!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • It changes my time from 16:54:03 to 11:54:03 UTC. which I dont want. I want time as it is. – parita porwal Feb 17 '17 at 11:00
  • 1
    then you need to format it with the timezone and whatever you want, I guess that was just an example how to parse it, not to format it for your output. since you didn't say what you ant to to with the date. – xander Feb 17 '17 at 11:45
1

You need to use ZZ instead of just Z for the timezone information.

i.e.

DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").parseDateTime("2016-07-19T16:54:03.000+05:30")

Taken from the Javadoc:

The count of pattern letters determine the format.

Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id.

Community
  • 1
  • 1
DB5
  • 13,553
  • 7
  • 66
  • 71
  • java.lang.IllegalArgumentException: Invalid format: "2016-07-19T16:54:03.000+05:30" is malformed at "05:30" exception – parita porwal Feb 20 '17 at 07:37
  • 1
    @paritaporwal, Sorry there was a typo in the pattern the "+" Symbol shouldn't be there. The line should be DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").parseDateTime("2016-07-19T16:54:03.000+05:30"). Have edit the answer to reflect this change. – DB5 Feb 20 '17 at 08:33
  • Thanks a lot...it works...... – parita porwal Feb 20 '17 at 08:54
0

You can try java.text.DateFormat

String DEFAULT_DATE_PARSE_PATTERN="dd.MM.yyyy";
DateFormat format = new SimpleDateFormat(DEFAULT_DATE_PARSE_PATTERN);
Date result = format.parse(your_value);
Take_Care_
  • 1,957
  • 1
  • 22
  • 24