简体   繁体   English

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

[英]How to convert string to datetime in java using joda time

I am currently working on converting from date to string. 我目前正致力于将日期转换为字符串。 After that I convert that string to datetime. 之后我将该字符串转换为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);

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);

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

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