Reputation: 1725
/**
* Gets an instance of GMT Calendar.
*
* @return a new <code>Calendar</code> object
*/
public static Calendar getGMTCalendar()
{
return Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
}
/**
* @return The month (eg. Calenday.MAY) value for the date.
*/
public static int getMonth(Date date)
{
Calendar c = getGMTCalendar();
System.out.println("date ::"+date.toString());
c.setTime(date);
int month=c.get(Calendar.MONTH);
System.out.println("date after calendar is set ::"+c.getTime()+",Month="+month);
return c.get(Calendar.MONTH);
}
Above is the code snipped I am using.When I try retrieving the month of the date I am passing to getMonth() like
int month=DateUtil.getMonth(date); (date is 10-01-2010)
The month I am expecting is 8(0-Jan,1-Feb...8-Sept,9-oct) but what I get here is month=8. I tried debugging and found that in the function getMonth() when i set the time using c.setTime(date) the date is set to 09-31-2010 i.e a day before the date passed. I am using INtellij Idea as the Ide Can anyone help??
Upvotes: 2
Views: 3442
Reputation: 1500525
Okay, now we've got the real data out, the problem is with your initial date.
Personally I find it easiest to diagnose this sort of thing using Joda Time:
import org.joda.time.*;
public class Test {
public static void main(String[] args)
{
DateTime dt = new DateTime(1285871400000L,
DateTimeZone.UTC);
System.out.println(dt);
}
}
That will definitely show everything in UTC... and it prints 2010-09-30T18:30:00.000Z. So the instant you're passing into the calendar is in September, not October. It's giving you the right result for the data you're giving it, as you've specified a GMT time zone - you're just not giving it the data you thought you were.
You need to understand that Date
just represents an instant in time, with no reference to calendar system or time zone. So while that date value printed out October 1st for you because of your default time zone, it really is still the instant which is in the evening of September 30th in UTC in the ISO calendar.
To be honest, if you can possibly use Joda Time instead of the built-in calendar types, you should... but you still need to be careful of the system default time zone being applied when you don't want it to be.
Upvotes: 3
Reputation: 86774
If you're in a timezone with a negative offset (i.e. the US, for example) and set the GMT date to the first day of a month with time 00:00:00, the local time will be in the previous day (and previous month). Check to make sure you aren't retrieving the local time from the Calendar object.
Upvotes: 0