简体   繁体   English

"如何从 Java 8 中的 LocalDateTime 获取毫秒数"

[英]How to get milliseconds from LocalDateTime in Java 8

I am wondering if there is a way to get current milliseconds since 1-1-1970 (epoch) using the new LocalDate<\/code> , LocalTime<\/code> or LocalDateTime<\/code> classes of Java 8.我想知道是否有一种方法可以使用 Java 8 的新LocalDate<\/code> 、 LocalTime<\/code>或LocalDateTime<\/code>类来获取自 1970 年 1 月 1 日(纪元)以来的当前毫秒数。

The known way is below:已知方法如下:

long currentMilliseconds = new Date().getTime();

I'm not entirely sure what you mean by "current milliseconds" but I'll assume it's the number of milliseconds since the "epoch," namely midnight, January 1, 1970 UTC.我不完全确定你所说的“当前毫秒”是什么意思,但我假设它是自“纪元”以来的毫秒数,即 UTC 时间 1970 年 1 月 1 日午夜。

If you want to find the number of milliseconds since the epoch right now, then use System.currentTimeMillis() as Anubian Noob has pointed out .如果您想立即找到自纪元以来的毫秒数,请使用System.currentTimeMillis()正如Anubian Noob 指出的那样 If so, there's no reason to use any of the new java.time APIs to do this.如果是这样,就没有理由使用任何新的 java.time API 来执行此操作。

However, maybe you already have a LocalDateTime or similar object from somewhere and you want to convert it to milliseconds since the epoch.但是,也许您已经有一个LocalDateTime或来自某处的类似对象,并且您想将其转换为自纪元以来的毫秒数。 It's not possible to do that directly, since the LocalDateTime family of objects has no notion of what time zone they're in. Thus time zone information needs to be supplied to find the time relative to the epoch, which is in UTC.无法直接执行此操作,因为LocalDateTime对象系列不知道它们所在的时区。因此需要提供时区信息以查找相对于 UTC 的时代的时间。

Suppose you have a LocalDateTime like this:假设你有一个像这样的LocalDateTime

LocalDateTime ldt = LocalDateTime.of(2014, 5, 29, 18, 41, 16);

You need to apply the time zone information, giving a ZonedDateTime .您需要应用时区信息,给出ZonedDateTime I'm in the same time zone as Los Angeles, so I'd do something like this:我和洛杉矶在同一时区,所以我会做这样的事情:

ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/Los_Angeles"));

Of course, this makes assumptions about the time zone.当然,这是对时区的假设。 And there are edge cases that can occur, for example, if the local time happens to name a time near the Daylight Saving Time (Summer Time) transition.并且存在可能发生的边缘情况,例如,如果本地时间恰好命名为接近夏令时(夏令时)转换的时间。 Let's set these aside, but you should be aware that these cases exist.让我们把这些放在一边,但你应该知道这些情况是存在的。

Anyway, if you can get a valid ZonedDateTime , you can convert this to the number of milliseconds since the epoch, like so:无论如何,如果您可以获得有效的ZonedDateTime ,您可以将其转换为自纪元以来的毫秒数,如下所示:

long millis = zdt.toInstant().toEpochMilli();

What I do so I don't specify a time zone is,我这样做我没有指定时区是,

System.out.println("ldt " + LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
System.out.println("ctm " + System.currentTimeMillis());

gives

ldt 1424812121078 
ctm 1424812121281

As you can see the numbers are the same except for a small execution time.如您所见,除了执行时间较短外,数字是相同的。

Just in case you don't like System.currentTimeMillis, use Instant.now().toEpochMilli()以防万一您不喜欢 System.currentTimeMillis,请使用Instant.now().toEpochMilli()

To avoid ZoneId you can do:为避免 ZoneId,您可以执行以下操作:

LocalDateTime date = LocalDateTime.of(1970, 1, 1, 0, 0);

System.out.println("Initial Epoch (TimeInMillis): " + date.toInstant(ZoneOffset.ofTotalSeconds(0)).toEpochMilli());

Getting 0 as value, that's right!得到 0 作为值,没错!

Since Java 8 you can call java.time.Instant.toEpochMilli() .从 Java 8 开始,您可以调用java.time.Instant.toEpochMilli()

For example the call例如调用

final long currentTimeJava8 = Instant.now().toEpochMilli();

gives you the same results as给你相同的结果

final long currentTimeJava1 = System.currentTimeMillis();

You can use java.sql.Timestamp also to get milliseconds.您也可以使用java.sql.Timestamp来获取毫秒。

LocalDateTime now = LocalDateTime.now();
long milliSeconds = Timestamp.valueOf(now).getTime();
System.out.println("MilliSeconds: "+milliSeconds);

要以毫秒为单位(自纪元以来)获取当前时间,请使用System.currentTimeMillis()

你可以试试这个:

long diff = LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();

If you have a Java 8 Clock, then you can use clock.millis() (although it recommends you use clock.instant() to get a Java 8 Instant, as it's more accurate).如果您有 Java 8 时钟,那么您可以使用clock.millis() (尽管它建议您使用clock.instant()来获取 Java 8 Instant,因为它更准确)。

Why would you use a Java 8 clock?为什么要使用 Java 8 时钟? So in your DI framework you can create a Clock bean:所以在你的 DI 框架中你可以创建一个 Clock bean:

@Bean
public Clock getClock() {
    return Clock.systemUTC();
}

and then in your tests you can easily Mock it:然后在您的测试中,您可以轻松地模拟它:

@MockBean private Clock clock;

or you can have a different bean:或者你可以有一个不同的bean:

@Bean
public Clock getClock() {
    return Clock.fixed(instant, zone);
}

which helps with tests that assert dates and times immeasurably.这有助于进行不可估量地断言日期和时间的测试。

Why didn't anyone mentioned the method LocalDateTime.toEpochSecond() :为什么没有人提到LocalDateTime.toEpochSecond()方法:

LocalDateTime localDateTime = ... // whatever e.g. LocalDateTime.now()
long time2epoch = localDateTime.toEpochSecond(ZoneOffset.UTC);

This seems way shorter that many suggested answers above...这似乎比上面的许多建议答案要短得多......

  default LocalDateTime getDateFromLong(long timestamp) {
    try {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
    } catch (DateTimeException tdException) {
      //  throw new 
    }
}

default Long getLongFromDateTime(LocalDateTime dateTime) {
    return dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
}

For LocalDateTime I do it this way:对于 LocalDateTime 我这样做:

LocalDateTime.of(2021,3,18,7,17,24,341000000)
    .toInstant(OffsetDateTime.now().getOffset())
    .toEpochMilli()

Date and time as String to Long (millis):日期和时间作为字符串到长(毫秒):

String dateTimeString = "2020-12-12T14:34:18.000Z";

DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);

LocalDateTime localDateTime = LocalDateTime
        .parse(dateTimeString, formatter);

Long dateTimeMillis = localDateTime
        .atZone(ZoneId.systemDefault())
        .toInstant()
        .toEpochMilli();

I think this is more simpler:我认为这更简单:

ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault());
Assert.assertEquals(System.currentTimeMillis(), zdt.toInstant().toEpochMilli());

get the millis like System.currentTimeMillis() (from UTC).获取类似 System.currentTimeMillis() 的毫秒数(来自 UTC)。

There are some methods available that no one has mentioned here.有一些可用的方法在这里没有人提到。 But I don't see a reason why they should not work.但我看不出他们不应该工作的原因。

In case of LocalDate<\/code> , you can use the toEpochDay()<\/code> method.对于LocalDate<\/code> ,您可以使用toEpochDay()<\/code>方法。 It returns the number of days since 01\/01\/1970.它返回自 1970 年 1 月 1 日以来的天数。 That number then can be easily converted to milliseconds:然后该数字可以轻松转换为毫秒:

long dateInMillis = TimeUnit.DAYS.toMillis(myLocalDate.toEpochDays());

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

相关问题 Java LocalDateTime 从 UTC 时区中删除毫秒 - Java LocalDateTime remove the milliseconds from UTC timezone 为什么从LocalDateTime获取毫秒与从Calendar获取日期之间存在差异? - Why are diferences between get milliseconds from LocalDateTime and Date from Calendar? Java 8 LocalDateTime-如何在字符串转换中保留.000毫秒 - Java 8 LocalDateTime - How to keep .000 milliseconds in String conversion Java - 从 Double 获取 LocalDateTime - Java - Get LocalDateTime from Double LocalDateTime 到 Java 8 和 Java 11 中的毫秒差异 - LocalDateTime to milliseconds difference in Java 8 and Java 11 如何在 Java 8 上使用 LocalDateTime.now() 获取当前的 LocalDateTime 包括秒数 - How to get the current LocalDateTime including seconds with LocalDateTime.now() on Java 8 LocalDateTime的毫秒数 - Milliseconds to LocalDateTime Java:使用LocalDateTime和ChronoUnit的时间差(以毫秒为单位) - Java: time difference in milliseconds using LocalDateTime and ChronoUnit 比较Java中的时间(以毫秒为单位)和LocalDateTime之间的时间 - Comparing time in java between epoch milliseconds and LocalDateTime 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象中获取第二个? - How to get the second from LocalDateTime objects in a method with return type LocalDateTime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM