如何通过Java找到午夜过去的秒数? [英] How can I find the amount of seconds passed from the midnight with Java?

查看:86
本文介绍了如何通过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 now = ZonedDateTime.now();
ZonedDateTime midnight = now.atStartOfDay()
Duration duration = Duration.between(midnight, now);
long secondsPassed = duration.getSeconds();

如果您使用的是Java 7或更低版​​本,则必须通过日历从午夜获取日期,然后减去。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆