255

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?

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
Tom
  • 2,561
  • 2
  • 15
  • 4
  • 2
    For anyone arriving here looking for how to parse date Strings using the `java.time` package in Java 8, try using [`LocalDateTime.parse`](http://stackoverflow.com/a/22463063/2646526) or `Instant.parse`. – heenenee Jul 26 '16 at 21:11
  • 2
    FYI, the [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 30 '17 at 23:22

10 Answers10

501

Use DateTimeFormat:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);
JodaStephen
  • 60,927
  • 15
  • 95
  • 117
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • Thanks for the reply :).That worked with formatter.parseDateTime. As per the API there is no parse method for DateTimeFormatter. – Tom Jun 06 '11 at 14:36
  • 2
    Hi, is it possible that the formatter doesn't accept timezones? "zz" returns "MEZ", when applying the `toString` function, but I cannot parse from it: `Invalid format: "31. Januar 2013 06:38:08 MEZ" is malformed at "MEZ"`. Is this a known issue? How can I avoid it? Regards. – Danyel Jan 31 '13 at 05:40
  • 2
    @Danyel: You can add timezones like this DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .withLocale(Locale.ROOT) .withChronology(ISOChronology.getInstanceUTC()); – Hyque Apr 17 '13 at 10:22
  • 2
    I get an Invalid format: "2014-11-04T17:41:52.000+01:00" is malformed at "+01:00" with the following formatter: private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'ZZ'"); DATE_TIME_FORMATTER.parseDateTime((String) customSoftware.get(header[3])) on joda-time 2.2 – Stephane Nov 08 '14 at 07:21
  • Still the same after upgrading to joda-time 2.5 – Stephane Nov 08 '14 at 10:55
  • 2
    After removing the single quotes around the ZZ it worked. I wonder what these single quotes mean... – Stephane Nov 08 '14 at 17:13
  • 2
    @StephaneEybert (or anyone else) The single quotes mean that something is a literal character to be expected in the string, and is not to be considered part of the pattern. For instance: if your date comes in as "2015-08-dd30" for some reason, you would specify "yyyy-MM-'dd'dd", indicating that the first dd is a literal part expected in the string, and the second dd (outside of the apostrophes) is the actual day that needs to be parsed. So in your earlier case it would have worked if instead of the actual timezone you would have put "ZZ" at the end of your incoming datetime-string. – SadBunny Aug 30 '15 at 03:46
  • 1
    `DateTimeFormatter` and `DateTimeFormat` not found here. Any suggestion? – Anderson Madeira Oct 17 '15 at 13:11
  • Is this still valid in Java 8? – wizlog Sep 02 '16 at 13:10
  • Date date = formatter.parseDateTime(string).toDate(); – Ravi Nov 21 '19 at 06:41
67

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"));
stephen.hanson
  • 9,014
  • 2
  • 47
  • 53
20
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");
Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114
Shawn Vader
  • 12,285
  • 11
  • 52
  • 61
18

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);
Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Ali Karaca
  • 3,365
  • 1
  • 35
  • 41
14

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");
Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30
5

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();
}
valentin_nasta
  • 596
  • 4
  • 23
efirat
  • 3,679
  • 2
  • 39
  • 43
  • 3
    kirlisakal doesn't in this case, but don't create a shared instance of a SimpleDateFormat as it isn't thread-safe, it is a nightmare to debug if you do – dannrob Jun 13 '13 at 13:12
  • 2
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), `java.util.Calendar`, and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). And the java.time classes are thread-safe, unlike the legacy classes. – Basil Bourque Dec 30 '17 at 23:29
4

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

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

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
Mark Tozzi
  • 10,353
  • 5
  • 22
  • 30
2

An simple method :

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

    return dateRetour;
}
Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
sissi49
  • 135
  • 1
  • 11
1

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
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
  • Both of therm outdated. There is a modern way too; it’s in [the answer by Basil Bourque](https://stackoverflow.com/a/48038725/5772882). Also you aren’t contributing anything that isn’t already in several other answers. And when Joda-Time is asked for, suggesting the even longer outdated and notoriously troublesome `SimpleDateFormat` is *bad* in my most honest opinion. – Ole V.V. Jul 26 '18 at 07:02