Why does SimpleDateFormat show unix date as December 31 1969?

时间:2015-07-28 23:07:22

标签: java android date

I am working on a date picker where there is a range of dates. I noticed that all of my dates are a day behind and while investigating the issue I narrowed down the problem to the SimpleDateFormat object. No matter what Unix time I give it it sets the date to the previous day. An example of this behaviour is

String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);

Log.d(TAG, "Time Zone: " + cal.getTimeZone().getDisplayName());
Log.d(TAG, "Printable: " + sdf.format(0));

The output that I see in the logger is

Time Zone: UTC
Printable: 12/31/1969

Why does the formatter use December 31 instead of January 1st 1970?

1 个答案:

答案 0 :(得分:5)

Because the DateFormat also has a TimeZone (and your system isn't set to UTC). You can change it with DateFormat.setTimeZone(TimeZone). Something like

String myFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Printable: " + sdf.format(0));

Output is (as you expected)

Printable: 01/01/1970