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.
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
See more on this question at Stackoverflow