I am working on a project that fetches Date/Time from backend in IST
(Indian standard Time) as shown "2013-01-09T19:32:49.103+05:30"
. However when i parse it using following DateFormat
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
followed by parsing..
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
System.out.println("XYZ ==============>"+date);
its Displaying date in GMT format as output i.e
Wed Jan 09 14:02:49 GMT+00:00 2013.
I have tried it using TimeZone class as..
TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);
but no effect..
How could i get a Date
class Object having Date in IST
format instead of GMT...
Please provide an appropriate solution..
EDIT:
This is how Code Looks Like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
String formattedDate=sdf.format(date);
System.out.println("XYZ ==============>"+formattedDate);
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss. SSSZ");
Calendar calendar = new GregorianCalendar(TimeZone. getTimeZone("GMT")); DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); formatter. setTimeZone(TimeZone.
Use setTimezone() method specifically to set the timezone.
Date does not have any time zone. It is just a holder of the number of milliseconds since January 1, 1970, 00:00:00 GMT. Take the same DateFormat that you used for parsing, set IST timezone and format your date as in the following example
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
output
2013-01-09T19:32:49.103+05:30
Note that XX
X pattern is used for ISO 8601 time zone (-08:00) since 1.7. If you are in 1.6 try Z
. See SimpleDateFormat API for details of format patterns
How could i get a Date class Object having Date in IST format instead of GMT...
You can't. Date
doesn't have a format or a time zone. It simply represents a number of milliseconds since the Unix epoch of midnight on January 1st 1970 UTC. Instead, Date.toString()
always uses the default time zone.
To use a specific format and time zone, use DateFormat
instead of Date.toString()
. You can set the time zone with DateFormat.setTimeZone()
and then convert a Date
to a String
using DateFormat.format()
. DateFormat
itself has some factory methods for creation, or you can use SimpleDateFormat
if you want to specify a particular pattern.
As Abu says, Joda Time is a much better date/time API than the built-in one, although for just formatting a date/time the standard library doesn't do a bad job. Just note that DateFormat
and its subclasses are generally not thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With