java的系統時間,怎麼計算從現在到淩晨還剩下多少時間?

來源:互聯網
上載者:User

標籤:sys   java   date   add   class   span   public   str   second   

Apache commons-lang3

long milliSecondsLeftToday = 86400000 -     DateUtils.getFragmentInMilliseconds(Calendar.getInstance(), Calendar.DATE);

 

 

System.currentTimeMillis() 是零時區的時間戳記,所以你要加上8個小時才行。
最基礎的寫法:

public class Main {    public static void main(String[] args) {        long hour = 60 * 60 * 1000;        long time = System.currentTimeMillis();        System.out.println(time);        time += 8 * hour;         System.out.println(time);        time %= 24 * hour;        System.out.printf("%02d:%02d\n", time / hour, time % hour / 60000);        time = 24 * hour - time;        System.out.printf("%02d:%02d\n", time / hour, time % hour / 60000);    }}

在當前時區有夏令時的情況下,另外一個用System.currentTimeMillis() 的答案是不能正確處理的,比如15年美國夏令時從3月8號淩晨2點開始,如果現在時間是3月8號1點,那種方式計算出來的就是錯誤的,而Calendar API可以正確處理,雖然很難用。

Calendar c = Calendar.getInstance();long now = c.getTimeInMillis();c.add(Calendar.DAY_OF_MONTH, 1);c.set(Calendar.HOUR_OF_DAY, 0);c.set(Calendar.MINUTE, 0);c.set(Calendar.SECOND, 0);c.set(Calendar.MILLISECOND, 0);long millis = c.getTimeInMillis() - now;

 

 

Java8中的寫法

LocalTime midnight = LocalTime.MIDNIGHT;LocalDate today = LocalDate.now();LocalDateTime todayMidnight = LocalDateTime.of(today, midnight);LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1);System.out.println(TimeUnit.NANOSECONDS.toSeconds(Duration.between(LocalDateTime.now(), tomorrowMidnight).toNanos()));

 

https://www.zhihu.com/question/28475461

 



 

java的系統時間,怎麼計算從現在到淩晨還剩下多少時間?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.