簡體   English   中英

Java:Unix時間,以秒為單位,以毫秒為單位

[英]Java: Unix time in seconds to milliseconds

我從一個json文件中獲得了10位數字的時間戳,而我剛發現這是Unix時間, 以秒為單位,而不是以毫秒為單位

因此,我進入DateUtils類,將以秒為單位的時間戳乘以1000,以便將其轉換為以毫秒為單位的時間戳。

當我嘗試測試isToday()時,這行代碼給了我大約50000英鎊的年費……

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

這是什么錯誤?

DateUtils.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;
    }
}

問題出在以下代碼塊中:

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

您將時間乘以1000兩次; 刪除* 1000之一,那么您應該可以:)

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。他們現在不需要。

根據其他要求,您可能希望實例實例是ZonedDateTime而不是Instant 在這種情況下,只需將atZone調用放入構造函數中,而不是將其放在isToday方法中即可。

鏈接Oracle教程: Date Time說明如何使用java.time。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM