Java 如何获得今天到目前为止经过的毫秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6476065/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:15:23  来源:igfitidea点击:

How to get the number of milliseconds elapsed so far today

javaandroid

提问by Chirag

I want to get the current time and date in milliseconds. How can I get this?

我想以毫秒为单位获取当前时间和日期。我怎样才能得到这个?

I tried this:

我试过这个:

Date date=new Date() ;  
System.out.println("Today is " +date.getTime());

It will return the milliseconds from the 1 Jan 1970.

它将返回 1970 年 1 月 1 日的毫秒数。

But I want the current millisecods of the today's date, like:

但我想要今天日期的当前毫秒数,例如:

23:59:00 = 86340000 milliseconds

采纳答案by Jordan Wade

This is not the correct approach for Java 8 or newer.This answer is retained for posterity; for any reasonably modern Java use Basil Bourque's approach instead.

这不是 Java 8 或更新版本的正确方法。这个答案为后人保留;对于任何合理的现代 Java,请改用 Basil Bourque 的方法。



The following seems to work.

以下似乎有效。

Calendar rightNow = Calendar.getInstance();

// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
    rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
    (24 * 60 * 60 * 1000);

System.out.println(sinceMidnight + " milliseconds since midnight");

The problem is that date.getTime()returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date()gives the current localtime. Adding the ZONE_OFFSETand DST_OFFSETfrom the Calendarclass gives you the time in the default/current time zone.

问题是date.getTime()从 1970-01-01T00:00:00Z 返回毫秒数,但new Date()给出当前本地时间。从类中添加ZONE_OFFSET和为您提供默认/当前时区的时间。DST_OFFSETCalendar

回答by Zéychin

Try:

尝试:

(d.getTime() % (86400000))

Note: 86400000 is the number of milliseconds in a day.

注意:86400000 是一天的毫秒数。

回答by Balaji.K

Use this code to get the current date and time

使用此代码获取当前日期和时间

DateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
        Calendar calendar=Calendar.getInstance();
        Date date=calendar.getTime();
        date.getHours();
        date.getMinutes();
        date.getMonth();
        date.getSeconds();
        date.getYear();

回答by Basil Bourque

java.time

时间

The modern approach uses java.timeclasses that supplant the troublesome old legacy date-time classes.

现代方法使用java.time类来取代麻烦的旧的遗留日期时间类。

Getting the span of time from the beginning of today to the current moment is more complicated that you might expect.

获取从今天开始到当前时刻的时间跨度比您想象的要复杂得多。

Current moment

当前时刻

First, determining “today” requires a time zone. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

首先,确定“今天”需要一个时区。时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的伪区域,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the JVM's current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtimeby any code in any thread of any app within the JVM.

如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为JVM 中任何应用程序的任何线程中的任何代码都可能在运行时随时更改默认值。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM's current default time zone.

The ZonedDateTimeclass represents a moment (a date & time-of-day) as seen by the people of a particular region (a time zone, a ZoneId).

ZonedDateTime类代表一个特定区域的人民看到一个时刻(日期和时间的日)(时区,一个ZoneId)。

ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Start of day

一天的开始

Next we need to determine the first moment of the day. Do not assume the day starts at 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day in a particular zone on a particular date.

接下来我们需要确定一天中的第一个时刻。不要假设一天从 00:00:00 开始。由于夏令时 (DST) 等异常情况,一天可能会在另一个时间开始,例如 01:00:00。让 java.time 确定特定日期特定区域中一天中的第一时刻。

First extract the date-only portion of our ZonedDateTimeobject above.

首先提取ZonedDateTime上面对象的仅日期部分。

LocalDate ld = zdt.toLocalDate() ;

Ask for first moment of the day in our desired zone.

在我们想要的区域中询问一天中的第一个时刻。

ZonedDateTime zdtStartOfDay = ld.atStartOfDay( z ) ;

Elapsed time

已用时间

Now we have the pair of pieces we need: first moment of the day, and the current moment. We ask the ChronoUnitenum object MILLISECONDSto calculate the time elapsed between that pair. Note that this may involve data loss, as the ZonedDateTimeobjects may hold microseconds or nanoseconds being ignored in this calculation of milliseconds.

现在我们有了我们需要的两个片段:一天中的第一个时刻和当前时刻。我们要求ChronoUnit枚举对象MILLISECONDS计算该对之间经过的时间。请注意,这可能涉及数据丢失,因为ZonedDateTime在此毫秒计算中,对象可能会保持微秒或纳秒被忽略。

long millisElapsedToday = ChronoUnit.MILLISECONDS.between( zdtStartOfDay , zdt ) ;

You may also be interested in representing that span-of-time as unattached to the timeline in a Durationobject.

您可能还想将该时间跨度表示为与Duration对象中的时间线无关。

Duration d = Duration.between( zdtStartOfDay , zdt ) ;


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

With a JDBC drivercomplying with JDBC 4.2or later, you may exchange java.timeobjects directly with your database. No need for strings or java.sql* classes.

使用符合JDBC 4.2或更高版本的JDBC 驱动程序,您可以直接与您的数据库交换java.time对象。不需要字符串或 java.sql* 类。

Where to obtain the java.time classes?

从哪里获得 java.time 类?

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 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多