[英]How to convert a date to milliseconds
我想将String myDate = "2014/10/29 18:10:45"
转换为long ms (ie currentinmlilies)
? 我在谷歌上找它,但我只能找到如何将ms转换为date 。
注意:为了清楚起见,我想从 1970/1/1 格式的日期中获取毫秒。
你没有Date
,你有一个日期的String
表示。 您应该将String
转换为Date
,然后获取毫秒。 要将String
转换为Date
,反之亦然,您应该使用SimpleDateFormat
类。
这是您想要/需要做的一个示例(假设此处不涉及时区):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
不过,要小心,因为在 Java 中获得的毫秒数是所需时期和 1970-01-01 00:00:00 之间的毫秒数。
使用自 Java 8 起可用的新日期/时间 API:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
LocalDateTime.parse( // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
"2014/10/29 18:10:45" // Convert input string to comply with standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in the middle with a `T`.
.replace( "/" , "-" ) // Replace SLASH in the middle with a `-`.
)
.atZone( // Apply a time zone to provide the context needed to determine an actual moment.
ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.toEpochMilli() // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.
1414602645000
接受的答案是正确的,只是它忽略了time zone 的关键问题。 您的输入字符串是在巴黎还是蒙特利尔的下午 6:10? 还是UTC ?
使用正确的时区名称。 通常是一个大陆加上城市/地区。 例如, "Europe/Oslo"
。 避免使用既不标准化也不唯一的 3 或 4 个字母代码。
现代方法使用java.time类。
更改您的输入以符合ISO 8601标准。 用T
替换中间的空格。 并用连字符替换斜线字符。 java.time类在解析/生成字符串时默认使用这些标准格式。 所以不需要指定格式模式。
String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
LocalDateTime
与您的输入字符串一样,缺少任何时区概念或与 UTC 的偏移量。 如果没有区域/偏移量的上下文, LocalDateTime
就没有真正的意义。 印度、欧洲或加拿大是下午 6:10 吗? 这些地方中的每一个都会在不同的时刻、时间轴上的不同点经历下午 6:10。 因此,如果要确定时间轴上的特定点,则必须指定要考虑的内容。
ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
现在我们有一个特定的时刻,在ZonedDateTime
中。 通过提取Instant
转换为 UTC。 Instant
类表示UTC时间线上的时刻,分辨率为纳秒(最多九 (9) 位小数)。
Instant instant = zdt.toInstant() ;
现在,我们可以获得自 1970 年 UTC 第一时刻的纪元参考 1970-01-01T00:00Z 以来所需的毫秒数。
long millisSinceEpoch = instant.toEpochMilli() ;
请注意可能的数据丢失。 Instant
对象能够承载微秒或纳秒,比毫秒更精细。 在获取毫秒数时,将忽略一秒的小数部分。
java.time框架内置于 Java 8 及更高版本中。 这些类取代了麻烦的旧日期时间类,例如java.util.Date
、 Calendar
和SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参阅Oracle 教程。 并在 Stack Overflow 上搜索许多示例和解释。 规范是JSR 310 。
您可以直接与您的数据库交换java.time对象。 使用符合JDBC 4.2或更高版本的JDBC 驱动程序。 不需要字符串,不需要java.sql.*
类。
从哪里获得 java.time 类?
ThreeTen-Extra项目通过附加类扩展了 java.time。 该项目是未来可能添加到 java.time 的试验场。 您可以在这里找到一些有用的类,例如Interval
、 YearWeek
、 YearQuarter
等等。
更新: Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。 我将保留这部分完整的历史。
下面是相同类型的代码,但使用Joda-Time 2.5 库和处理时区。
java.util.Date、.Calendar 和 .SimpleDateFormat 类是出了名的麻烦、混乱和缺陷。 避开他们。 使用 Java 8 中内置的 Joda-Time 或 java.time 包(受 Joda-Time 启发)。
您的字符串几乎是 ISO 8601 格式。 斜杠需要是连字符,中间的空格应该替换为T
。 如果我们对其进行调整,那么生成的字符串可以直接输入到构造函数中,而无需指定格式化程序。 Joda-Time 使用 ISO 8701 格式作为解析和生成字符串的默认格式。
String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();
SimpleDateFormat类允许您将String
解析为java.util.Date
对象。 拥有 Date 对象后,您可以通过调用Date.getTime()
获取自纪元以来的毫秒数。
完整的例子:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
请注意,这会给您一个long
而不是 double,但我认为这可能是您的意图。 SimpleDateFormat
类的文档有大量关于如何设置它来解析不同格式的信息。
2017 年的答案是:使用 Java 8 中引入的日期和时间类(并且在ThreeTen Backport中也向后移植到 Java 6 和 7)。
如果要解释计算机时区中的日期时间字符串:
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
如果是另一个时区,请填写该区域而不是ZoneId.systemDefault()
。 如果是 UTC,请使用
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
.atOffset(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
您可以使用 LocalDateTime 和 DateTimeFormatter 解决问题
String date = "21/04/2022 12:42:29";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
LocalDateTime dt = LocalDateTime.parse(date, formatter);
System.out.println(dt.toEpochSecond(ZoneOffset.UTC));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.