简体   繁体   English

如何获得当前自午夜以来的毫秒数?

[英]How can I get the count of milliseconds since midnight for the current?

Note, I do NOT want millis from epoch.请注意,我不想要纪元的毫秒。 I want the number of milliseconds currently on the clock.我想要时钟上当前的毫秒数。

So for example, I have this bit of code.例如,我有这段代码。

Date date2 = new Date(); 
Long time2 = (long) (((((date2.getHours() * 60) + date2.getMinutes())* 60 ) + date2.getSeconds()) * 1000);

Is there a way to get milliseconds with date?有没有办法用日期获得毫秒? Is there another way to do this?有没有另一种方法可以做到这一点?

Note: System.currentTimeMillis() gives me millis from epoch which is not what I'm looking for.注意: System.currentTimeMillis()给了我来自纪元的毫秒数,这不是我要找的。

Do you mean?你的意思是?

long millis = System.currentTimeMillis() % 1000;

BTW Windows doesn't allow timetravel to 1969顺便说一句,Windows 不允许时间旅行到 1969 年

C:\> date
Enter the new date: (dd-mm-yy) 2/8/1969
The system cannot accept the date entered.

Use Calendar使用日历

Calendar.getInstance().get(Calendar.MILLISECOND);

or要么

Calendar c=Calendar.getInstance();
c.setTime(new Date()); /* whatever*/
//c.setTimeZone(...); if necessary
c.get(Calendar.MILLISECOND);

In practise though I think it will nearly always equal System.currentTimeMillis()%1000;在实践中,我认为它几乎总是等于 System.currentTimeMillis()%1000; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.除非有人有闰毫秒或某些日历定义的纪元不在第二边界上。

Calendar.getInstance().get(Calendar.MILLISECOND);

I tried a few ones above but they seem to reset @ 1000我尝试了上面的几个,但它们似乎重置@ 1000

This one definately works, and should also take year into consideration这个肯定有效,还应该考虑到年份

long millisStart = Calendar.getInstance().getTimeInMillis();

and then do the same for end time if needed.如果需要,然后在结束时间做同样的事情。

tl;dr tl;博士

You ask for the fraction of a second of the current time as a number of milliseconds ( not count from epoch).您要求将当前时间的几分之一秒作为毫秒数(从纪元开始计算)。

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z → 113 2017-04-25T03:01:14.113Z → 113

  1. Get the fractional second in nanoseconds (billions).获取以纳秒(十亿)为单位的小数秒。
  2. Divide by a thousand to truncate to milliseconds (thousands).除以一千以截断为毫秒(千)。

See this code run live at IdeOne.com .查看此代码在 IdeOne.com 上实时运行

Using java.time使用 java.time

The modern way is with the java.time classes.现代方法是使用 java.time 类。

Capture the current moment in UTC.以 UTC 格式捕获当前时刻。

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField .使用Instant.get方法查询TemporalField的值。 In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND .在我们的例子中,我们想要的TemporalFieldChronoField.MILLI_OF_SECOND

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.或者自己算一下。

More likely you are asking this for a specific time zone.您更有可能在特定时区询问此问题。 The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.一秒钟的几分之一可能与Instant相同,但时区有很多异常,我对做出这个假设犹豫不决。

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second.询问小数秒。 The Question asked for milliseconds , but java.time classes use a finer resolution of nanoseconds .问题要求毫秒,但 java.time 类使用更精细的纳秒分辨率。 That means the number of nanoseconds will range from from 0 to 999,999,999.这意味着纳秒数的范围从 0 到 999,999,999。

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million.如果您真的想要毫秒,请通过除以一百万来截断更精细的数据。 For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.例如,半秒是 500,000,000 纳秒,也是 500 毫秒。

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

About java.time关于 java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

Where to obtain the java.time classes?从哪里获得 java.time 类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目用额外的类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

  1. long timeNow = System.currentTimeMillis();
  2. System.out.println(new Date(timeNow));

2014 年 4 月 4 日星期五 14:27:05 PDT

Joda-Time乔达时间

I think you can use Joda-Time to do this.我认为你可以使用Joda-Time来做到这一点。 Take a look at the DateTime class and its getMillisOfSecond method.查看DateTime类及其getMillisOfSecond方法。 Something like就像是

int ms = new DateTime().getMillisOfSecond() ;

In Java 8 you can simply do在 Java 8 中,你可以简单地做

ZonedDateTime.now().toInstant().toEpochMilli()

returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z返回:自 1970-01-01T00:00:00Z 纪元以来的毫秒数

I did the test using java 8 It wont matter the order the builder always takes 0 milliseconds and the concat between 26 and 33 milliseconds under and iteration of a 1000 concatenation我使用 java 8 进行了测试 构建器总是需要 0 毫秒的顺序和 26 到 33 毫秒之间的连接以及 1000 连接的迭代无关紧要

Hope it helps try it with your ide希望它可以帮助您尝试使用 ide

public void count() {

        String result = "";

        StringBuilder builder = new StringBuilder();

        long millis1 = System.currentTimeMillis(),
            millis2;

        for (int i = 0; i < 1000; i++) {
            builder.append("hello world this is the concat vs builder test enjoy");
        }

        millis2 = System.currentTimeMillis();

        System.out.println("Diff: " + (millis2 - millis1));

        millis1 = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            result += "hello world this is the concat vs builder test enjoy";
        }

        millis2 = System.currentTimeMillis();

        System.out.println("Diff: " + (millis2 - millis1));
    }

Java 8:爪哇 8:

LocalDateTime toDate = LocalDateTime.now();
LocalDateTime fromDate = LocalDateTime.of(toDate.getYear(), toDate.getMonth(), 
toDate.getDayOfMonth(), 0, 0, 0);
long millis = ChronoUnit.MILLIS.between(fromDate, toDate);

You can use java.util.Calendar class to get time in milliseconds.您可以使用 java.util.Calendar 类以毫秒为单位获取时间。 Example:例子:

Calendar cal = Calendar.getInstance();
int milliSec = cal.get(Calendar.MILLISECOND);
// print milliSec

java.util.Date date = cal.getTime();
System.out.println("Output: " +  new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM