user3190153 user3190153 - 3 months ago 11x
Java Question

Get the alphanumeric month value for a timezone enabled DateTime instance

I have a linux server which is set to use UTC time as it is based in the UK. I have a piece of java code which runs at the New York time of 22:00 on the last day of June. This means in the UK, it would be the next day of the next month.

I want to retrieve the alphanumeric month (January, February, etc) from the DateTime instance, but for the America/New_York date. Currently, the below code gives me the UK month of July, but I want it to give me June as the DateTime is set to America/New_York.

DateFormat fullMonthFormat = new SimpleDateFormat("MMMM");
DateTime dt1 = new DateTime();
dt1 = dt1.withZone(DateTimeZone.forID("America/New_York"));

For example. If i was to run this on 30/06/2016 22:00 New York time, the println statement will give me the value 'July'. How can I obtain the correct month text, which should be June?


You need to set the time zone into fullMonthFormat, since you want the month of New York. The DateFormat is using the local time (UTC) if you want to format any date to a specific Time Zone you need to set that particular Time Zone to the DateFormat object.

So it should look like this:

DateFormat fullMonthFormat = new SimpleDateFormat("MMMM");
DateTime dt1 = new DateTime();
DateTimeZone dtz = DateTimeZone.forID("America/New_York");
dt1 = dt1.withZone(dtz);