[java] Converting a date string to a DateTime object using Joda Time library

I have a date as a string in the following format "04/02/2011 20:27:05". I am using Joda-Time library and would like to convert it to DateTime object. I did:

DateTime dt = new DateTime("04/02/2011 20:27:05")

But I'm getting the following error :

Invalid format: "04/02/2011 14:42:17" is malformed at "/02/2011 14:42:17"

How to convert the above date to a DateTime object?

This question is related to java datetime jodatime

The answer is


I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:

DateTime date = DateTime.parse("04/02/2011 20:27:05", 
                  DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));

tl;dr

java.time.LocalDateTime.parse( 
    "04/02/2011 20:27:05" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
)

java.time

The modern approach uses the java.time classes that supplant the venerable Joda-Time project.

Parse as a LocalDateTime as your input lacks any indicator of time zone or offset-from-UTC.

String input = "04/02/2011 20:27:05" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

ldt.toString(): 2011-02-04T20:27:05

Tip: Where possible, use the standard ISO 8601 formats when exchanging date-time values as text rather than format seen here. Conveniently, the java.time classes use the standard formats when parsing/generating strings.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

There are two ways this could be achieved.

DateTimeFormat

DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");

SimpleDateFormat

        String dateValue = "04/02/2011 20:27:05";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //  04/02/2011 20:27:05

        Date date = sdf.parse(dateValue); // returns date object
        System.out.println(date); // outputs: Fri Feb 04 20:27:05 IST 2011

From comments I picked an answer like and also adding TimeZone:

String dateTime = "2015-07-18T13:32:56.971-0400";

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
        .withLocale(Locale.ROOT)
        .withChronology(ISOChronology.getInstanceUTC());

DateTime dt = formatter.parseDateTime(dateTime);

You need a DateTimeFormatter appropriate to the format you're using. Take a look at the docs for instructions on how to build one.

Off the cuff, I think you need format = DateTimeFormat.forPattern("M/d/y H:m:s")


An simple method :

public static DateTime transfStringToDateTime(String dateParam, Session session) throws NotesException {
    DateTime dateRetour;
    dateRetour = session.createDateTime(dateParam);                 

    return dateRetour;
}

Your format is not the expected ISO format, you should try

DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime time = format.parseDateTime("04/02/2011 20:27:05");

You can also use SimpleDateFormat, as in DateTimeFormat

Date startDate = null;
Date endDate = null;
try {
    if (validDateStart!= null) startDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateStart + " " + validDateStartTime);
    if (validDateEnd!= null) endDate = new SimpleDateFormat("MM/dd/yyyy HH:mm", Locale.ENGLISH).parse(validDateEnd + " " + validDateEndTime);
} catch (ParseException e) {
    e.printStackTrace();
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to jodatime

Comparing two joda DateTime instances How to format Joda-Time DateTime to only mm/dd/yyyy? Joda DateTime to Timestamp conversion How to find difference between two Joda-Time DateTimes in minutes Convert LocalDate to LocalDateTime or java.sql.Timestamp String to LocalDate Converting a date string to a DateTime object using Joda Time library Convert from java.util.date to JodaTime Number of days between two dates in Joda-Time Difference in days between two dates in Java?