如何在Java中将字符串日期转换为长整型?

huangapple go评论56阅读模式
英文:

How to convert date in string to Long in java?

问题

我有一个模型中以字符串格式表示的日期和时间
`"startTime": "2022-10-19T14:31:22+00:00"`

我该如何在Java中将其转换为长格式

我尝试使用
`'Long.valueOf(startTime)''Long.parseLong(startTime)'` 这两个函数

但两者都引发了异常

"在java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)"
英文:

I have date and time in string format in one of my models.
"startTime": "2022-10-19T14:31:22+00:00"

How can I convert it to long format in Java?

I tried using
'Long.valueOf(startTime)' and 'Long.parseLong(startTime)' are two functions.

but in both I am getting an exception.

"at the java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)" 

答案1

得分: 5

你可以使用内置方法解析日期时间格式,也可以将其转换为长整型值(假设自纪元以来的秒数)。

Instant.parse("2022-10-19T14:31:22+00:00").getEpochSecond()

请参阅 https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Instant.html

查看代码运行在 Ideone.com

英文:

You can parse your datetime format using builtin methods - also to convert it to a long value (assuming the number of seconds since the epoch).

Instant.parse("2022-10-19T14:31:22+00:00").getEpochSecond()

See https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/time/Instant.html

See code run at Ideone.com.

huangapple
  • 本文由 发表于 2023年2月6日 04:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定