如何使用joda时间在java中将字符串转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26564192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:49:16  来源:igfitidea点击:

How to convert string to datetime in java using joda time

javajodatime

提问by chemat92

I am currently working on converting from date to string. After that I convert that string to datetime. But it error. Anyone can help me?

我目前正在将日期转换为字符串。之后我将该字符串转换为日期时间。但它错误。任何人都可以帮助我吗?

Here is the code.

这是代码。

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


SimpleDateFormat outFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dt1 = outFormat.format(date1);


DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(dt1);

采纳答案by Makoto

You're doing entirely too much work. Joda Time can convert for you in its parse(String, DateTimeFormatter)method.

你做的工作太多了。Joda Time 可以在其parse(String, DateTimeFormatter)方法中为您转换。

DateTime dateTime = DateTime.parse(dt1, formatter);

Alternatively, if your string were in ISO8601 format (that is, yyyy-MM-dd'T'HH:mm:ssZ), you could just use parse(String)instead:

或者,如果您的字符串采用 ISO8601 格式(即yyyy-MM-dd'T'HH:mm:ssZ),您可以parse(String)改为使用:

DateTime dateTime = DateTime.parse(dt1);