Java:Unix时间以毫秒为单位

问题描述 投票:0回答:2

我从一个json文件中获得了一个10位数的时间戳,我刚刚发现这是Unix时间,以秒为单位而不是毫秒。

所以我去了我的DateUtils类,以秒为单位将时间戳乘以1000,以便将其转换为以毫秒为单位的时间戳。

当我尝试测试isToday()时,这行代码给了我一年像50000的东西......

int otherYear = this.calendar.get(Calendar.YEAR);

这里有什么错误?

date U替LS.Java

public class DateUtils{

 public class DateUtils {
    private Calendar calendar;

    public DateUtils(long timeSeconds){
        long timeMilli = timeSeconds * 1000;
        this.calendar = Calendar.getInstance();
        this.calendar.setTimeInMillis(timeMilli*1000);
    }
    private boolean isToday(){
        Calendar today = Calendar.getInstance();
        today.setTimeInMillis(System.currentTimeMillis());

        // Todays date
        int todayYear = today.get(Calendar.YEAR);
        int todayMonth = today.get(Calendar.MONTH);
        int todayDay = today.get(Calendar.DAY_OF_MONTH);

        // Date to compare with today
        int otherYear = this.calendar.get(Calendar.YEAR);
        int otherMonth = this.calendar.get(Calendar.MONTH);
        int otherDay = this.calendar.get(Calendar.DAY_OF_MONTH);

        if (todayYear==otherYear && todayMonth==otherMonth && todayDay==otherDay){
            return true;
        }
        return false;
    }
}
java calendar unix-timestamp java-calendar
2个回答
2
投票

问题出在这个代码块中:

    long timeMilli = timeSeconds * 1000;
    this.calendar = Calendar.getInstance();
    this.calendar.setTimeInMillis(timeMilli*1000);

你将时间乘以两倍;删除其中一个* 1000,你应该很高兴去:)


0
投票
public class DateUtils {
    private Instant inst;

    public DateUtils(long timeSeconds) {
        this.inst = Instant.ofEpochSecond(timeSeconds);
    }

    private boolean isToday() {
        ZoneId zone = ZoneId.systemDefault();

        // Todays date
        LocalDate today = LocalDate.now(zone);

        // Date to compare with today
        LocalDate otherDate = inst.atZone(zone).toLocalDate();

        return today.equals(otherDate);
    }
}

另一个答案是正确的。我发布这个告诉你,Calendar类已经过时了,它在java.time中的替换,现代Java日期和时间API,使用起来更好,并提供更简单和更清晰的代码。作为一个细节,它接受自Unix时代以来的秒数,所以你不需要乘以1000.你可能会想,没什么大不了的,但是在理解为什么你乘以1000之前,一个或另一个读者仍然需要三思而后行他们现在不需要。

根据其他要求,您可能希望将实例varibale设为ZonedDateTime而不是Instant。在这种情况下,只需将atZone调用放入构造函数中,而不是在isToday方法中使用它。

链接:Oracle Tutorial: Date Time解释如何使用java.time。

© www.soinside.com 2019 - 2024. All rights reserved.