Custom format for java.time.LocalDate is throwing DateTimeParseException [duplicate] - java

This question already has answers here:
Unable to Convert String to localDate with custom pattern [duplicate]
(1 answer)
How to format LocalDate object to MM/dd/yyyy and have format persist
(4 answers)
Why am I getting a parse exception when I try to parse the current LocalDateTime [duplicate]
(2 answers)
Closed 1 year ago.
I would like to parse a date format YYYY-MM-DD into the following MMM dd, yyyy.
This is my part of code which is causing DateTimeParseException - >
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("MMM dd, yyyy"); LocalDate localDate = LocalDate.parse("2002-10-01",dateTimeFormatter1);
The exception message when I try to parse the date with the given format is:
Method threw 'java.time.format.DateTimeParseException' exception. Text '2002-10-01' could not be parsed at index 0.

That's because 2002-10-01 is in format YYYY-MM-DD, so trying to parse (i.e. convert it to a LocalDate object) it with format MMM dd, yyyy isn't going to work.
You need two formats to do this:
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("MMM dd, yyyy");
LocalDate localDate = LocalDate.parse("2002-10-01",dateTimeFormatter1);
String newRepresentation = dateTimeFormatter2.format(localDate);
System.out.println(newRepresentation);

Your exception was caused by your specified parsing format "MMM dd, yyyy" not matching the input 2002-10-01.
You commented:
I would need to have it as an LocalDate object in MMM dd, yyyy format
A LocalDate does not have a “format”. Text has a format, but LocalDate is not text.
The LocalDate class can parse an incoming string to produce a LocalDate object. And a LocalDate object can generate a string that represents its value. But a LocalDate object itself is neither of those strings. LocalDate has its own internal representation of a date, the details of which do not concern us.
You said:
I would like to parse a date format YYYY-MM-DD
That format complies with the ISO 8601 standard. The java.time classes use those standard formats by default when parsing/generating text. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2002-10-01" ) ;
You said
… into the following MMM dd, yyyy.
Generally better to let java.time automatically localize rather than you hard-code a specific format.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = ld.format( f ) ;

Related

Change date format Java getting Unparseable date Error

I have a date in the following format:
lastUpdatedDate = "12/14/2021 09:15:17";
I used the following code/format to convert date into yyyy-MM-dd hh:mm:ss format:
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
But it gives me below error:
java.text.ParseException: Unparseable date: "12/14/2021 09:15:17"
output should be: 2021-12-14 09:15:17
How can I achieve this?
Change the format to
SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date lastUpdatedDateFormatted = dt.parse(lastUpdatedDate);
System.out.println(lastUpdatedDateFormatted);
And it should be able to parse the date then.
As you are wanting to display or output the date in yyyy-MM-dd HH:mm:ss format, you should parse the date first then format the date to desired format.
try {
String lastUpdatedDate = "12/14/2021 09:15:17";
Date lastDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(lastUpdatedDate);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lastDate));
} catch (ParseException e) {
e.printStackTrace();
}
Your formatting pattern fails to match your input string.
And you are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
The modern solution uses the java.time classes.
Your input lacks an indicator of time zone or offset from UTC, so parse as a LocalDateTime object.
LocalDateTime ldt =
LocalDateTime
.parse(
"12/14/2021 09:15:17" ,
DateTimeFormatter.ofPattern( "MM/dd/uuuu hh:mm:ss" ) ;
) ;
Your desired output is nearly compliant with the ISO 8601 standard format used by default in java.time, except for that SPACE in the middle rather than T.
String output = ldt.toString().replace( "T" , " " ) ;

java.time.format.DateTimeParseException for dd-MMM-yy format

I am trying for hours now to parse this String to LocalDate and I just can't find where my pattern is wrong.
public void parseDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd'-'MMM'-'yy");
LocalDate date = LocalDate.parse("05-Sep-20", formatter);
}
I get the following exception:
java.time.format.DateTimeParseException: Text '05-Sep-20' could not be parsed at index 3
It works fine when using the pattern dd'-'MMMM'-'yy or dd'-'MM'-'yy, but it just won't work for MMM
I used the single quotes around the dash, because otherwise I was getting a parsing exception at a different index.
I am using Java1.8 and java.time
It could be your locale. Try this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd'-'MMM'-'yy", Locale.US);
LocalDate date = LocalDate.parse("05-Sep-20", formatter);
ref: https://stackoverflow.com/a/44928297

How do I Date format for dd MMM yyyy, as in 01 Apr 2020 [duplicate]

This question already has answers here:
java DateTimeFormatterBuilder fails on testtime [duplicate]
(2 answers)
Closed 2 years ago.
I have a pdf file where I want to know if the next line is a date, or just a string (there are two types of formats of the listing, and knowing if I've arrived at a date is important.) The trouble is, there appears to be no way to use date formatting to arrive at a date of 01 Apr 2020
LocalDate date = parseDate( "dd MMM yyyy", "01 Apr 2020" );
Throws ... Text '01 Apr 2020' could not be parsed at index 3
private static LocalDate parseDate( final String format, final String s ) {
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
LocalDate ld; // Check if this was a legal LocalDate.
try {
ld = LocalDate.parse(s, df);
} catch (java.time.format.DateTimeParseException pe) {
System.out.println( pe.getMessage() );
ld = null; // This will signal an error
}
return ld;
}
Is there really no way to parse that format of date, like a bank uses in their pdf?
Replace
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format );
With
final DateTimeFormatter df = DateTimeFormatter.ofPattern( format , Locale.US );
Hopefully, this will resolve your issue.
I believe you're using java8, You can do
LocalDate date = LocalDate.parse("01 Apr 2020", DateTimeFormatter.ofPattern("dd MMM yyyy", Locale.ROOT));
Edited: After pointed out that it doesn't work for all locales. Locale.ROOT should be used for neutral locale.

Java String to Date object of the format “MM/dd/yyyy HH:mm:ss a”

I need to convert a String containing a date into a date object.
The String will be in the format "yyyy-mm-dd HH:mm:ss" and I want the "MM/dd/yyyy HH:mm:ss a " format as result.
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateString , formatter);
The code above is throwing an exception.
You have to use two Formatter, one to covert String to LocalDateTime and the other to format this date as you want :
From String to LocalDateTime :
String dateString = "2018-03-20 09:31:31";
LocalDateTime date = LocalDateTime.parse(
dateString,
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
);
Now From LocalDateTime to String :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
String newDate = date.format(formatter);
System.out.println(newDate);// 03/20/2018 09:31:31 AM
Note : You have to use LocalDateTime instead of just LocalDate, your format contain both date and time, not just date, else you will get an error :
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
That's a common error, based on the misconception that dates have formats - but they actually don't.
Date/time objects have only values, and those values - usually numerical - represent the concept of a date (a specific point in the calendar) and a time (a specific moment of the day).
If you have a String, then you don't actually have a date. You have a text (a sequence of characters) that represents a date. Note that all of the strings below are different (they have a different sequence of characters), but all represent the same date (the same values, the same point in the calendar):
2018-03-20 09:31:31
03/20/2018 9:31:31 AM (using USA's format: month/day/year)
Tuesday, March 20th 2018, 09:31:31 am
and many others...
What you want to do is to get one format (one String, one text representing a date) and transform it to another format (anoter String, another different sequence of characters that represents the same date).
In Java (and in many other languages - if not all - btw) you must do it in 2 steps:
convert the String to a date/time object (convert the text to the numerical values) - that's what the parse method does
convert the date/time object to another format (convert the numerical values to another text)
That said, when you call the parse method, you're trying to transform a String (a text, a sequence of characters) into a date/time object. This means that the DateTimeFormatter must have a pattern that matches the input.
The input is 2018-03-20 09:31:31, which is year-month-day hour:minute:second. And the formatter you used to parse it has the pattern MM/dd/yyyy HH:mm:ss a (month/day/year hour:minute:second am/pm).
You used the output pattern (the one that should be used in step 2) to parse the input. That's why you've got an exception: the formatter tried to parse a month with 2 digits followed by a / when the input actually contains a year with 4 digits followed by a -.
You must use a different DateTimeFormatter for each step, using the correct pattern for each case. YCF_L's answer has the code that does the job, I'd just like to add one little detail. The formatter used for the output (step 2) is:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy HH:mm:ss a", Locale.ENGLISH
);
Note that HH is used for the hours. Take a look at the javadoc and you'll see that uppercase HH represents the hour-of-day fields (values from 0 to 23 - so 1 AM is printed as 01 and 1 PM is printed as 13).
But you're also printing the AM/PM field (the a in the pattern), so maybe what you need is actually the lowercase hh, which is the clock-hour-of-am-pm (values from 1 to 12) or even KK (hour-of-am-pm (values from 0 to 11)).
String dateString = "2018-03-20 09:31:31";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateInString);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String reportDate = df.format(date );
} catch (ParseException e) {
e.printStackTrace();
}
You need to do a 2 steps conversion:
from your String date time in the wrong format to a (tempoary) LocalDateTime object.
if you still want to only extract the date (Year-Month-day) do a LocalDateTime.toLocalDate()
From this LocalDateTime object into the your String object in the right format
String dateString = "2018-03-20 09:31:31";
DateTimeFormatter formatterForWrongFormat = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(" ")
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
//1- from String(wrong format) into datetime object
LocalDateTime dateTime = LocalDateTime.parse(dateString , formatterForWrongFormat);
// 1.1 extract date object (Optional)
LocalDate myDate = dateTime.toLocalDate();
// 2- now from your LocalDateTime to the String in the RIGHT format
DateTimeFormatter formatterForRightFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a",
Locale.ENGLISH);
System.out.println("right format: "+dateTime.format(formatterForRightFormat));
you can test this code here
You can use the SimpleDateFormatter which is easier to implement and permit you to change the format of your date easily.
More here : What are the date formats available in SimpleDateFormat class?
Hope this will help you !

Parse datetime without offset in OffsetDateTime java

Can I somehow parse a datetime that's without offset using OffsetDateTime.parse(....)
Java code:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX");
OffsetDateTime date = OffsetDateTime.parse("2017-02-03 12:30:3000", FORMATTER);
I'm getting datetime as a String without offset, but need to parse it into OffsetDateTime, I know I need an offset here, but can I some how alter that String to insert default/dummy offset (maybe +00:00) & parse it using OffsetDateTime. The problem is that object has to be OffsetDateTime.
The simplest solution is to parse your string into a LocalDateTime and then convert:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
OffsetDateTime date = LocalDateTime.parse("2017-02-03 12:30:30", formatter)
.atOffset(ZoneOffset.UTC);
This gives an OffsetDateTime of 2017-02-03T12:30:30Z, where Z means UTC or offset zero.
You can parse directly into an OffsetDateTime if you want:
DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss")
.parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
.toFormatter();
OffsetDateTime date = OffsetDateTime.parse("2017-02-03 12:30:30", FORMATTER);
Finally, if you are required to use the formatter given in the question, altering the string to fit is of course an option. For example:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS XXX");
String fixedDateTimeString
= "2017-02-03 12:30:3000".replaceFirst("(\\d{2})0*$", "$1.000 +00:00");
OffsetDateTime date = OffsetDateTime.parse(fixedDateTimeString, FORMATTER);
As you can see, in the last example I have also kept the too many zeroes in the string I am using as a starting point, removing them in the same operation that appends the offset. The result is the same, 2017-02-03T12:30:30Z.
Edit: uuuu or yyyy for year in the format pattern string? Since the year is always in the common era (Anno Domini), either works. yyyy is for year of era and would be right of there was an era designator (like AD or BC, format pattern letter G). uuuu is a signed year, where year 0 means 1 BCE, -1 means 2 BCE, etc. There’s more in this question: uuuu versus yyyy in DateTimeFormatter formatting pattern codes in Java?
Actually I achieved it by:
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
OffsetDateTime.of(LocalDateTime.parse("2017-02-03 12:30:30", FORMATTER), ZoneOffset.UTC);

Categories