java:日历没有获得正确的日期/时间?

标签 java calendar

我使用此代码将日期字符串转换为 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/

相关文章:

java - 使用 Java 8 java.time.LocalDate,你可以计算农历新年日期吗?

python `YYYY-MM-DD`

javascript - 获取今天的科普特日期

android - 从日历中减去天数

java - JPA 避免在插入之前加载对象

java - wait()和sleep()的区别

java - 使用对象列表作为字段覆盖类的哈希码方法

java - 使用日历对象显示日期

java - 谷歌云端点 EOFException

java - 如何在文本中打印变量值