Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to datetime in java using joda time

Tags:

java

jodatime

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);
like image 340
chemat92 Avatar asked Oct 25 '14 15:10

chemat92


People also ask

Can we convert string to date in Java?

We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes.

What is Joda-Time in Java?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.

What is Joda-Time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.

Is Joda DateTime deprecated?

So the short answer to your question is: YES (deprecated).


1 Answers

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

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:

DateTime dateTime = DateTime.parse(dt1);
like image 156
Makoto Avatar answered Nov 14 '22 21:11

Makoto