本文介绍了如何在java中找到自1970年以来的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个实时项目,我需要在1970年1月1日之后找到秒数。我使用下面的代码来查找秒数,但结果是错误的。代码如下。

iam working with a real time project where i got a requirement to find seconds since 1970 january 1.I have used the following code to find out seconds but is giving wrong result.The code is as follows.

public long returnSeconds(int year, int month, int date) {
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.set(1970, 01, 01);
    calendar2.set(year, month, date);
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long seconds = diff / 1000;
    return seconds;
}

在上面代替年,月, date 我正在传递 2011,10,1 并且iam得到

In the above in place of year,month,date I'm passing 2011,10,1 and iam getting

1317510000

但正确的答案是

1317427200

有关此问题的任何帮助对我来说非常有用。

Any help regarding this is very useful to me.

推荐答案

根据你的愿望 1317427200 作为输出,有几个问题需要解决。

Based on your desire that 1317427200 be the output, there are several layers of issue to address.


  • 首先,正如其他人所提到的,java已经使用了UTC 1 / 1/1970时代。除非您有奇怪的区域设置规则,否则通常无需计算时期并执行减法。

  • First as others have mentioned, java already uses a UTC 1/1/1970 epoch. There is normally no need to calculate the epoch and perform subtraction unless you have weird locale rules.

其次,当您创建新日历时,它会初始化为'now '所以它包括一天中的时间。更改年/月/日不会影响时间字段。因此,如果您希望它代表日期的午夜,则需要在设置日期之前将日历归零。

Second, when you create a new Calendar it's initialized to 'now' so it includes the time of day. Changing the year/month/day doesn't affect the time of day fields. So if you want it to represent midnight of the date, you need to zero out the calendar before you set the date.

第三,您尚未指定你应该如何处理时区。夏令时可能导致特定日历日期所代表的绝对秒数差异,具体取决于JVM的运行位置。由于纪元是UTC,我们可能希望在UTC时间工作?您可能需要向您正在接口的系统的制造商寻求澄清。

Third, you haven't specified how you're supposed to handle time zones. Daylight Savings can cause differences in the absolute number of seconds represented by a particular calendar-on-the-wall-date, depending on where your JVM is running. Since epoch is in UTC, we probably want to work in UTC times? You may need to seek clarification from the makers of the system you're interfacing with.

第四,Java中的月数为零索引。 1月是0,10月是9。

Fourth, months in Java are zero indexed. January is 0, October is 9.

将所有这些放在一起

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;

会给你 1317427200

这篇关于如何在java中找到自1970年以来的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 10:06