Error in conversion of dates in java

String date = jsonobject.getString("needbydate");
DateFormat df = new SimpleDateFormat("MMM/dd/yyyy");
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
Date startDate = sdf.parse(date);
String needbydate = df.format(startDate).toString()+"";

What is happening::

  • At the start

date=2014-12-17T21:37:00+00:00

  • At the end

needbydate= Dec/18/2014

17 is changed to 18 .... What wrong am i doing in conversion


EDIT:

            String date=jsonobject.getString("needbydate");
            DateFormat df = new SimpleDateFormat("MMM/dd/yyyy",Locale.ENGLISH);
            DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss",Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date startDate;
            startDate = sdf.parse(date);
            needbydate = df.format(startDate).toString()+"";
Jon Skeet
people
quotationmark

Your date formats are using the system default time zone. That's okay for your input, because it specifies the UTC offset explicitly - but for your output, you've just got a date. So it's showing you the date that that point in time occurred in your system time zone.

You need to think about what time zone you want it to be - and whether that's affected by a non-zero offset in your input. You can use DateFormat.setTimeZone to set the time zone to be used on output. (For example, should 2014-12-17T21:37:00-05:00 show as December 18th (UTC) or December 17th (source time zone)?)

You should also be using HH in your input format instead of hh, as it's clearly a 24-hour value rather than a 12-hour value.

people

See more on this question at Stackoverflow