如何使用 Java 找到从午夜开始经过的秒数? [英] How can I find the amount of seconds passed from the midnight with Java?
本文介绍了如何使用 Java 找到从午夜开始经过的秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个函数来告诉我从午夜过去了多少秒.我目前正在使用 System.currentTimeMillis()
但它给了我类似 UNIX 的时间戳.
I need a function that gives me how many seconds passed from the midnight. I am currently using System.currentTimeMillis()
but it gives me the UNIX like timestamp.
如果我也能得到毫秒,那对我来说是一个奖励.
It would be a bonus for me if I could get the milliseconds too.
推荐答案
如果您使用 Java >= 8,这很容易做到:
If you're using Java >= 8, this is easily done :
ZonedDateTime nowZoned = ZonedDateTime.now();
Instant midnight = nowZoned.toLocalDate().atStartOfDay(nowZoned.getZone()).toInstant();
Duration duration = Duration.between(midnight, Instant.now());
long seconds = duration.getSeconds();
如果您使用的是 Java 7 或更低版本,则必须通过 Calendar 从午夜开始获取日期,然后减去.
If you're using Java 7 or less, you have to get the date from midnight via Calendar, and then substract.
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;
这篇关于如何使用 Java 找到从午夜开始经过的秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文