0

I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format. Now if I try to get the calendar day (i.e. 04 april 2015) it gets converted to my local timezone and prints the next day(i.e 05 april 2015). How do I get the calendar day in a particular time zone (say +1:30 GMT)? I am using the getdate()function from java.util.Date to get the calendar day.

1 Answers1

3

I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format.

No, you have a Date variable. That doesn't have any particular format. Ignore what toString() tells you - that's just formatting it in your local time zone, in a default format. That doesn't mean the format or time zone is part of the state of the Date object - that just represents a point in time.

It sounds like you want:

// Whatever pattern you want - ideally, specify the locale too
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Whatever time zone you want
format.setTimeZone(...);
String text = format.format(date);

Alternatively, if you just want a Calendar value:

TimeZone zone = ...; // Whatever time zone you want
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
// Now use calendar.get(Calendar.YEAR) etc
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The dates are being stored in the -7:00 GMT format. I need to validate some values against those dates. But when I try to get the calendar date, the date gets modified to my current timezone. Is there a way to by pass that? Also can I give the timezone as -7:00 or +5:30 (or will have to search a timezone that matches to the particular value)? – Lakshit Pande Jul 28 '15 at 13:21
  • @LakshitPande: "The dates are being stored in the -7:00 GMT format." Not in `java.util.Date` they're not. In `java.util.Date`, they're stored as a `long` value, which is the number of milliseconds since the unix epoch. I've given you code which will either display the value in whatever time zone you want, or give you a `Calendar` object you can use. It's not clear whether you've tried that code or not, or where your `Date` has come from. Use `SimpleTimeZone` to construct a time zone with a fixed offset - but be aware that that probably won't be useful in many places, as it won't observe DST. – Jon Skeet Jul 28 '15 at 13:24
  • thanks for the info. I did not properly understand the answer. The comments help. Thanks again. It works. – Lakshit Pande Jul 28 '15 at 13:38