这是一些示例代码。我明确地将我的服务器的默认时区设置为纽约时间,但您可能需要遵循 Jon Lin 的提示并确定您自己服务器的默认时区。例如,如果您在纽约,但使用托管在旧金山的服务器并使用太平洋时间,那么这可能与任何区域的预期时间相差 3 小时。
public void testTodayInIndia() {
// For demonstration, make my system act as though it's in New York
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
long oneDay = 86400000;
long fourYears = (365 * 4 + 1) * oneDay;
// Calculate 42 years after 1/1/1970 UTC
Date now = new Date(fourYears * 10 + oneDay * 365 * 2 + 1);
TimeZone calcutta = TimeZone.getTimeZone("Asia/Kolkata");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Since unspecified, this output will show the date and time in New York
assertEquals("2011-12-31 19:00:00", formatter.format(now));
// After setting the formatter's time zone, output reflects the same instant in Calcutta.
formatter.setTimeZone(calcutta);
assertEquals("2012-01-01 05:30:00", formatter.format(now));
}