Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to local date error

I am trying to convert from string to localdate(JODA TIME) but its giving me error

String theDate = w.getPSDate();  == 6/03/2013
LocalDate ld = new LocalDate(theDate);
System.out.println(ld);

for some reason, I have to use string instead of date. I want to print the date as (06/03/2013). what is the error in the code?

error

Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "06/03/2013" is malformed at "/03/2013"
at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:747)
at org.joda.time.convert.StringConverter.getPartialValues(StringConverter.java:87)
at org.joda.time.LocalDate.<init>(LocalDate.java:406)
at org.joda.time.LocalDate.<init>(LocalDate.java:354)
at Date.GetDate.main(GetDate.java:94)

Java Result: 1

like image 668
vijay Avatar asked Mar 12 '13 10:03

vijay


People also ask

How can I format local date?

LocalDate is an immutable class that represents Date with default format of yyyy-MM-dd. We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance.

How do I parse LocalDateTime?

parse(CharSequence text) parse() method of a LocalDateTime class used to get an instance of LocalDateTime from a string such as '2018-10-23T17:19:33' passed as parameter. The string must have a valid date-time and is parsed using DateTimeFormatter. ISO_LOCAL_DATE_TIME.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

Is DateTimeFormatter thread-safe?

Yes, it is: DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well. Implementation Requirements: This class is immutable and thread-safe.


1 Answers

Use a DateTimeFormatter instead:

// Are you sure it's 6/03/2013 rather than 06/03/2013? dd would be nicer...
DateTimeFormatter formatter = DateTimeFormat.forPattern("d/MM/yyyy");
LocalDate date = formatter.parseLocalDate(text);
like image 163
Jon Skeet Avatar answered Oct 13 '22 11:10

Jon Skeet