Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in conversion of dates in java

Tags:

java

android

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()+"";
like image 814
Devrath Avatar asked Dec 17 '14 11:12

Devrath


People also ask

How do I convert datetime to Date in java?

DateTimeFormatter formatter = DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm:ss z"); ZonedDateTime zonedDateTime = ZonedDateTime. parse("2015-05-05 10:15:30 Europe/Paris", formatter);

Can I convert a String in to a Date in java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.


2 Answers

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.

like image 77
Jon Skeet Avatar answered Sep 19 '22 00:09

Jon Skeet


With the help of JonSkeet resolved this ... Complete solution ...here

            String date=jsonobject.getString("needbydate");
            DateFormat df = new SimpleDateFormat("MMM/dd/yyyy",Locale.ENGLISH);
            df.setTimeZone(TimeZone.getTimeZone("UTC"));
            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();
like image 37
Devrath Avatar answered Sep 21 '22 00:09

Devrath