简体   繁体   English

在Java 8中将String转换为java.util.Date

[英]Convert String to java.util.Date in Java 8

Currently I have a requirement to convert String to java.util.Date . 目前,我需要将String转换为java.util.Date Found many tutorials to convert string to Date by using java.text.SimpleDateFormatter . 找到了许多教程,可以使用java.text.SimpleDateFormatterstring转换为Date But my concern in this SimpleDateFormatter is not thread safe. 但是我对此SimpleDateFormatter关注不是线程安全的。 Is there any possibility to convert string to java.util.Date by using java.time package in Java 8. Since java.time package classes are thread safe. 通过使用Java 8 java.util.Date的java.time包,可以将string转换为java.util.Date吗?因为java.time包类是线程安全的。

To answer the question about java.time from Java SE 8: 要回答来自Java SE 8的有关java.time的问题:

You could use: 您可以使用:

LocalDateTime date = LocalDateTime.parse(someDateString);

and to convert it to date you could use: 并将其转换为日期,您可以使用:

Instant instant = date.atZone(ZoneId.systemDefault()).toInstant();
Date res = Date.from(instant);

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

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