我使用此代码将日期字符串转换为 unix 时间戳:
int year = 2012;
int month = 2; // eg. for march
int day = 31;
int hrs = 0;
int min = 18;
这应该以英文表示法表示此日期/时间 31.3.2012 00:18 或 3/31/2012 00:18
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin")); // GMT+1
cal.set(year, month, day, hrs, min);
unixtime = cal.getTimeInMillis() / 1000;
unixtime的结果是:1333145929
如果我将其转换回来 (cal.setTimeInMillis(1333145929 * 1000);
) 我得到 30.3.2012 00:18
我输了一天!
最佳答案
如何打印日历
?
我认为您得到的 GMT 时间比格林威治标准时间晚一小时,因此午夜晚一天。
考虑:
public static void main(String[] args) throws Exception {
int year = 2012;
int month = 2; // eg. for march
int day = 31;
int hrs = 0;
int min = 18;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin")); // GMT+1
cal.set(year, month, day, hrs, min);
long time = cal.getTimeInMillis();
System.out.println(time);
cal.setTimeInMillis(time);
final DateFormat sdf = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL);
System.out.println(sdf.format(cal.getTime()));
}
输出:
1333145915825
Friday, 30 March 2012 23:18:35 o'clock BST
现在,如果我将 TimeZone
添加到 DateFormat
中:
final DateFormat sdf = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL);
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(sdf.format(cal.getTime()));
我得到:
1333145887761
Saturday, 31 March 2012 00:18:07 o'clock CEST
因此,SimpleDateFormat
在格式化时使用您的默认TimeZone
,而不是 的
(如您调用TimeZone
日历Calendar.getTime()
)。
关于java:日历没有获得正确的日期/时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17944846/