如何使用 Java 找到从午夜开始经过的秒数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4389500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find the amount of seconds passed from the midnight with Java?
提问by Utku Zihnioglu
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.
我需要一个函数来告诉我从午夜过去了多少秒。我目前正在使用,System.currentTimeMillis()
但它给了我类似 UNIX 的时间戳。
It would be a bonus for me if I could get the milliseconds too.
如果我也能获得毫秒,那对我来说将是一个奖励。
采纳答案by Valentin Rocher
If you're using Java >= 8, this is easily done :
如果您使用 Java >= 8,这很容易做到:
ZonedDateTime nowZoned = ZonedDateTime.now();
Instant midnight = nowZoned.toLocalDate().atStartOfDay(nowZoned.getZone()).toInstant();
Duration duration = Duration.between(midnight, Instant.now());
long seconds = duration.getSeconds();
If you're using Java 7 or less, you have to get the date from midnight via Calendar, and then substract.
如果您使用的是 Java 7 或更低版本,则必须通过 Calendar 从午夜开始获取日期,然后减去。
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;
回答by secmask
(System.currentTimeMillis()/1000) % (24 * 60 * 60)
回答by Peter Lawrey
Like @secmask, if you need milli-seconds since GMT midnight, try
像@secmask 一样,如果您需要从格林威治标准时间午夜开始的毫秒数,请尝试
long millisSinceGMTMidnight = System.currentTimeMillis() % (24*60*60*1000);
回答by jazzgil
The simplest and fastest method to get the seconds since midnight for the current timezone:
获取当前时区自午夜以来的秒数的最简单和最快的方法:
One-time setup:
一次性设置:
static final long utcOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis());
If you use Apache Commons, you can use DateUtils.DAY_IN_MILLIS, otherwise define:
如果使用 Apache Commons,则可以使用 DateUtils.DAY_IN_MILLIS,否则定义:
static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
And then, whenever you need the time...:
然后,只要你需要时间......:
int seconds = (int)((System.currentTimeMillis() + utcOffset) % DateUtils.DAY_IN_MILLIS / 1000);
Note that you'll need to re-setup if there's a possibility that your program will run long enough, and Daylight Saving Times change occurs...
请注意,如果您的程序有可能运行足够长的时间并且夏令时发生变化,您将需要重新设置...
回答by Przemek
java.time
时间
Using the java.time
framework built into Java 8 and later. See Tutorial.
使用java.time
内置于 Java 8 及更高版本中的框架。请参阅教程。
import java.time.LocalTime
import java.time.ZoneId
LocalTime now = LocalTime.now(ZoneId.systemDefault()) // LocalTime = 14:42:43.062
now.toSecondOfDay() // Int = 52963
It is good practice to explicit specify ZoneId
, even if you want default one.
显式指定是一种很好的做法ZoneId
,即使您想要默认的。
回答by Basil Bourque
tl;dr
tl;博士
Instant then = // Represent a moment in UTC.
ZonedDateTime // Represent a moment as seen through the wall-clock time used by the people of a particular region (a time zone).
.now( // Capture the current moment. Holds up to nanosecond resolution, but current hardware computer clocks limited to microseconds for telling current time.
ZoneId.of( "Africa/Casablanca" ) // Specify the time zone. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, `EST`.
) // Returns a `ZonedDateTime` object.
.toLocalDate() // Extract the date-only portion, without time-of-day and without time zone.
.atStartOfDay( // Deterimine the first moment of the day on that date in that time zone. Beware: The day does *not* always begin at 00:00:00.
ZoneId.of( "Africa/Casablanca" ) // Specify the time zone for which we want the first moment of the day on that date.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjusts from that time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
;
…
…
Duration // Represent a span-of-time unattached to the timeline in terms of hours-minutes-seconds.
.between( // Specify start and stop moments.
then , // Calculated in code seen above.
Instant.now() // Capture current moment in UTC.
) // Returns a `Duration` object.
.getSeconds() // Extract the total number of whole seconds accross this entire span-of-time.
java.time
时间
Java 8 and later has the java.time framework baked in.
Java 8 及更高版本内置了 java.time 框架。
By using ZonedDateTime
and time zone, we are handling anomalies such as Daylight Saving Time (DST). For example, in the United States a day can be 23, 24, or 25 hourslong. So the time until tomorrow can vary by ±1 hour from one day to another.
通过使用ZonedDateTime
和时区,我们正在处理夏令时 (DST)等异常情况。例如,在美国,一天可以是 23、24 或 25 小时。因此,到明天的时间可能会从一天到另一天相差 ±1 小时。
First get the current moment.
首先获取当前时刻。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( z );
Now extract the date-only portion, a LocalDate
, and use that date to ask java.time when that day began for our desired time zone. Do not assume the day began at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean that the day may begin at another time such as 01:00:00.
现在提取仅日期部分 a LocalDate
,并使用该日期向 java.time 询问我们所需时区的那一天何时开始。不要假设一天从 00:00:00 开始。夏令时 (DST) 等异常意味着一天可能在另一个时间开始,例如 01:00:00。
ZonedDateTime todayStart = now.toLocalDate().atStartOfDay( z ); // Crucial to specify our desired time zone!
Now we can get the delta between the current moment and the start of today. Such a span of time unattached to the timeline is represented by the Duration
class.
现在我们可以得到当前时刻和今天开始之间的增量。这种与时间线无关的时间跨度由Duration
类表示。
Duration duration = Duration.between( todayStart , now );
Ask the Duration
object for the total number of seconds in the entire span of time.
向Duration
对象询问整个时间跨度中的总秒数。
long secondsSoFarToday = duration.getSeconds();
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by darrenmc
Using JodaTime you can call:
使用 JodaTime,您可以调用:
int seconds = DateTime.now().secondOfDay().get();
int millis = DateTime.now().millisOfDay().get();
回答by pollaris
Use getTime().getTime() instead of getTimeInMillis() if you get an error about calendar being protected. Remember your imports:
如果您收到有关日历受到保护的错误,请使用 getTime().getTime() 而不是 getTimeInMillis()。记住你的进口:
import java.util.*;
will include them all while you are debugging:
将在您调试时包括所有这些:
Calendar now = Calendar.getInstance();
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
long ms = now.getTime().getTime() - midnight.getTime().getTime();
totalMinutesSinceMidnight = (int) (ms / 1000 / 60);