如何从当前时间获取当前毫秒数

时间:2023-01-02 02:14:46

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()提供给我millis from epoch,这不是我要找的。

9 个解决方案

#1


171  

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.

#2


24  

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; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.

在实践中,我认为它几乎总是等于System.currentTimeMillis()%1000;除非某人的时间间隔是毫秒,或者某些日历是用一个不是在第二个边界上的历元来定义的。

#3


16  

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

#4


10  

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.

然后在需要的时候做同样的事情。

#5


5  

tl;dr

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 - 25 t03:01:14.113z→113

  1. Get the fractional second in nanoseconds (billions).
  2. 以十亿分之一秒的速度获得分数秒。
  3. Divide by a thousand to truncate to milliseconds (thousands).
  4. 除以1000以截断为毫秒(千)。

See this code run live at IdeOne.com.

查看此代码运行在IdeOne.com。

Using java.time

The modern way is with the java.time classes.

现代的方法是使用java。时间类。

Capture the current moment in UTC.

捕获UTC中的当前时刻。

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

使用即时。获取用于查询时间字段值的方法。在我们的例子中,我们需要的临时字段是ChronoField.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.

更可能的情况是,你问的是一个特定的时区。一秒钟的时间很可能和瞬间发生的时间一样,但是时区有如此之多的异常,我不愿做出这样的假设。

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. That means the number of nanoseconds will range from from 0 to 999,999,999.

询问分数秒。问题要求毫秒,但是java。时间类使用更细的纳秒分辨率。这意味着纳秒的数量将从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.

如果你真的想要毫秒数,可以用100万除以更精确的数据。例如,半秒是5亿纳秒,也是500毫秒。

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java。时间框架构建在Java 8和之后。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议迁移到java。时间类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8和SE 9以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • ThreeTenABP项目特别适用于Android。
    • See How to use ThreeTenABP….
    • 看到如何使用ThreeTenABP ....
  • Android的ThreeTenABP项目专门针对Android开发了ThreeTen-Backport(上面提到过)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project 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.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#6


4  

  1. long timeNow = System.currentTimeMillis();
  2. 长timeNow = System.currentTimeMillis();
  3. System.out.println(new Date(timeNow));
  4. system . out。println(新日期(timeNow));

Fri Apr 04 14:27:05 PDT 2014

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

#7


2  

Joda-Time

I think you can use Joda-Time to do this. Take a look at the DateTime class and its getMillisOfSecond method. Something like

我想你可以用Joda-Time来做这个。查看DateTime类及其getMillisOfSecond方法。类似的

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

#8


0  

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 z开始的毫秒数

#9


0  

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));
    }

#1


171  

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.

#2


24  

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; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.

在实践中,我认为它几乎总是等于System.currentTimeMillis()%1000;除非某人的时间间隔是毫秒,或者某些日历是用一个不是在第二个边界上的历元来定义的。

#3


16  

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

#4


10  

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.

然后在需要的时候做同样的事情。

#5


5  

tl;dr

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 - 25 t03:01:14.113z→113

  1. Get the fractional second in nanoseconds (billions).
  2. 以十亿分之一秒的速度获得分数秒。
  3. Divide by a thousand to truncate to milliseconds (thousands).
  4. 除以1000以截断为毫秒(千)。

See this code run live at IdeOne.com.

查看此代码运行在IdeOne.com。

Using java.time

The modern way is with the java.time classes.

现代的方法是使用java。时间类。

Capture the current moment in UTC.

捕获UTC中的当前时刻。

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

使用即时。获取用于查询时间字段值的方法。在我们的例子中,我们需要的临时字段是ChronoField.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.

更可能的情况是,你问的是一个特定的时区。一秒钟的时间很可能和瞬间发生的时间一样,但是时区有如此之多的异常,我不愿做出这样的假设。

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. That means the number of nanoseconds will range from from 0 to 999,999,999.

询问分数秒。问题要求毫秒,但是java。时间类使用更细的纳秒分辨率。这意味着纳秒的数量将从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.

如果你真的想要毫秒数,可以用100万除以更精确的数据。例如,半秒是5亿纳秒,也是500毫秒。

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

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java。时间框架构建在Java 8和之后。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

现在处于维护模式的Joda-Time项目建议迁移到java。时间类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8和SE 9以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Java SE 6和SE 7大部分Java。在three10 - backport中,时间功能被反向移植到Java 6和7。
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • ThreeTenABP项目特别适用于Android。
    • See How to use ThreeTenABP….
    • 看到如何使用ThreeTenABP ....
  • Android的ThreeTenABP项目专门针对Android开发了ThreeTen-Backport(上面提到过)。看到如何使用ThreeTenABP ....

The ThreeTen-Extra project 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.

三个额外的项目扩展了java。时间和额外的类。这个项目是java.time未来可能增加的一个试验场。您可以在这里找到一些有用的课程,如间隔、年周、年季等。

#6


4  

  1. long timeNow = System.currentTimeMillis();
  2. 长timeNow = System.currentTimeMillis();
  3. System.out.println(new Date(timeNow));
  4. system . out。println(新日期(timeNow));

Fri Apr 04 14:27:05 PDT 2014

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

#7


2  

Joda-Time

I think you can use Joda-Time to do this. Take a look at the DateTime class and its getMillisOfSecond method. Something like

我想你可以用Joda-Time来做这个。查看DateTime类及其getMillisOfSecond方法。类似的

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

#8


0  

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 z开始的毫秒数

#9


0  

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));
    }