I have the code below:
package com.company.customer;
import java.util.*;
import java.text.*;
import java.io.*;
public class DateSample {
private TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
private SimpleDateFormat sdfDate = new SimpleDateFormat();
private Date inputDate;
private String dateInString = "2015-07-15";
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
public void datePrint() {
sdfDate.setTimeZone(GMT_TIMEZONE);
sdfDate.applyPattern("EE-ddMMM");
try {
inputDate = formatter.parse(dateInString);
} catch (Exception e) {
System.out.println("populateTabDates: ParseException");
}
String formatResults = sdfDate.format(inputDate);
// Modify the return to cut down the weekday: Fri-20Aug => Fr-20Aug
formatResults = formatResults.substring(0, 2) + formatResults.substring(3);
System.out.println(formatResults);
}
}
The problem appears when I set my PC to London timezone and change the PC hour to 8 or 9am. Then, the formatResults variable shows 14 instead of July 15; any thoughts?
You haven't set the time zone for formatter
, so that's whatever the system default time zone is.
So, you're parsing "2015-07-15" using the system default time zone. If that's London, you're parsed date is 2015-07-15T00:00:00+01 which is 2015-07-14T23:00:00Z. When you format that using the UTC time zone and just the date part, you're getting July 14th.
Put both formatters into the same time zone, basically, or you should expect a parse/format pair to "shift" the value. (This would be easier to see if you were also parsing and formatting the time of day.)
I'd also recommend using UTC
as the name of the UTC time zone instead of GMT
; the latter might confuse some people into thinking it's the UK time zone, which alternates between GMT and BST.
See more on this question at Stackoverflow