conversion from java sql date to java localdate - java

String oldDate = "04-07-19 02:41:39.063000000 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd-MM-YY HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.padNext(1)
.appendText(ChronoField.AMPM_OF_DAY)
.toFormatter();
LocalDate parseDate = LocalDate.parse(oldDate, formatter);
My date from the DB is "04-07-19 02:41:39.063000000 PM"
and i want to parse the date and convert it to my convenient form.
but when i try to parse the date using the DateTimeFormatter mentioned above the code throws exception..
the new date should be of the format mentioned below
String newDate = parseDate.format(DateTimeFormatter.ofPattern("dd-MMMM-uuuu"));
can someone help me to track the error?
exception iam getting is
Exception in thread "main" java.time.format.DateTimeParseException: Text '04-07-19 02:41:39.063000000 PM' could not be parsed at index 55

In your pattern you had few errors. First of all padNext() add a padding to a fixed width. In your case it should be 28 or something like that. I've just replaced it with appendLiteral(' '). Then HH represends hours in 24hour day, it won't work with AM/PM. Last thing was year, YY represends "week-based-year" according to JavaDoc (not exactly sure what that means) - had to change to yy for it to work.
Working pattern:
String oldDate = "04-07-19 02:41:39.063000000 PM";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd-MM-yy hh:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.appendLiteral(' ')
.appendText(ChronoField.AMPM_OF_DAY)
.toFormatter();
LocalDate parseDate = LocalDate.parse(oldDate, formatter);
System.out.println(parseDate);

Related

java.time.format.DateTimeParseException: Text '13/11/2020' could not be parsed at index 2

I'm facing a problem converting from string to LocalDateTime, and adding 3 months to the current month.
This is my code:
String str = "13/11/2020";
LocalDateTime dateTime = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
dateTime.plusMonths(3); // => output: 13/02/2021
System.out.println(dateTime);
But when I run it I get the following exception:
java.time.format.DateTimeParseException: Text '13/11/2020' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) ~[?:1.8.0_144]
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) ~[?:1.8.0_144]
at java.time.LocalDateTime.parse(LocalDateTime.java:492) ~[?:1.8.0_144]
How can I fix this problem ? Many thanks
Multiple issues:
Your String is look like a LocalDate and LocalDateTime, it doesn't contain the time part
The pattern you are using is not the same format as your String it should be dd/MM/yyyy or dd/MM/uuuu and not dd-MM-yyyy
To parse your String you need:
LocalDate date = LocalDate.parse(str, DateTimeFormatter.ofPattern("dd/MM/uuuu"));
dateTime = dateTime.plusMonths(3);
Or if you want LocalDateTime, then you can use DateTimeFormatterBuilder with 0 for hours, minutes and seconds:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd/MM/uuuu")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
dateTime = dateTime.plusMonths(3);
and the result will be like this: 2021-02-13T00:00
Note: dateTime.plusMonths(3) is immutable so to change the value you have to assign the new value to the variable.
There are several issues in your code:
You are using the wrong format pattern. If the date string contains slashes, so should the pattern string as well: DateTimeFormatter.ofPattern("dd/MM/yyyy").
If the date does not include time, then use LocalDate instead of LocalDateTime.
The plusMonths result needs to be assigned to a new variable to get the updated instance.
The DateTimeFormatter needs to be used when printing the expected result 13/02/2021, so you can share the same formatter instance:
String str = "13/11/2020";
var dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
var dateTime = LocalDate.parse(str, dateTimeFormatter);
var newDateTime = dateTime.plusMonths(3); // => output: 13/02/2021
System.out.println(newDateTime.format(dateTimeFormatter));

How to parse string (such as "Sunday, July 4, 2021") to LocalDate?

I am trying to parse a string "Sunday, July 4, 2021" to LocalDate as the following:
string this.selectedDate = "Sunday, July 4, 2021";
LocalDate date = LocalDate.parse(this.selectedDate);
But I am getting this error:
java.time.format.DateTimeParseException: Text 'Sunday, July 4, 2021' could not be parsed at index 0
How can I convert such a string full date to the LocalDate?
Try it like this.
String s = "Sunday, July 4, 2021";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEEE, LLLL d, yyyy");
LocalDate ld = LocalDate.parse(s, dtf);
System.out.println(ld);
prints
2021-07-04
Read up on DateTimeFormatter if you want to change the output format.
Note: If the day of the week is wrong for the numeric day of the month, you will get a parsing error. To avoid this, just skip over or otherwise ignore the day of the week.

java LocalDateTime parsing exception for date having pattern MM/d/yyyy HH:mm:ss a

I am getting exception while executing below code i am using java datetime APIs.
String strDate = "12/4/2018 5:26:28 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/d/yyyy HH:mm:ss a", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime.parse(strDate, formatter);
below exception is coming
Exception in thread "main" java.time.format.DateTimeParseException: Text '12/4/2018 5:26:28 PM' could not be parsed at index 10
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at Test.main(Test.java:20)
Your pattern specifies "HH" which is a 0-padded 24-hour hour of day. You want h: non-zero-padded, and "clock-hour-of-am-pm" (12-hour hour of day).
You almost never want HH or H in the same pattern as a.
In general, when you run into problems like this, you should look at your pattern really, really carefully and compare it with the description in the documentation.
Use hh for 12-hours format and match it up with 05.
String strDate = "12/4/2018 05:26:27 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/d/yyyy hh:mm:ss a", Locale.ENGLISH);
LocalDateTime localDateTime = LocalDateTime.parse(strDate, formatter);

Java java.time.format.DateTimeParseException on String

I am trying to parse a date to convert it to epochs. I tried the solution of a similar question here without success:
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLL dd yyyy").withLocale(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(date, formatter);
System.out.println(date+" "+ldt.toEpochSecond(ZoneOffset.UTC));
And I get Exception in thread "main" java.time.format.DateTimeParseException: Text 'Jun 4 2015' could not be parsed at index 0 even though I am fairly certain that my regular expression is correct. What am I missing here?
EDIT:
Following the comments, I changed LocalDateTime to LocalDate, but keep getting the same error:
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(date, formatter);
String date = "Jun 4 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);
LocalDate ldt = LocalDate.parse(date, formatter);
parses fine. Don't put the "dd" as it won't parse days less than 10. As #JB Nizet said, you'll need to use LocalDate, not LocalDateTime.

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

I am simply trying to convert a date string into a DateTime object in Java 8. Upon running the following lines:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime dt = LocalDateTime.parse("20140218", formatter);
I get the following error:
Exception in thread "main" java.time.format.DateTimeParseException:
Text '20140218' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor:
{},ISO resolved to 2014-02-18 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
The syntax is identical to what has been suggested here, yet I am served with an exception. I am using JDK-8u25.
It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);
If you really need to transform a date to a LocalDateTime object, you could use the LocalDate.atStartOfDay(). This will give you a LocalDateTime object at the specified date, having the hour, minute and second fields set to 0:
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDateTime time = LocalDate.parse("20140218", formatter).atStartOfDay();
For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter definition, e.g.:
private static DateTimeFormatter DATE_FORMAT =
new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
One should set the optional fields if they will appear. And the rest of code should be exactly the same.
Edit : usefull thing from wittyameta comment :
Remember to add the parseDefaulting AFTER you have called appendPattern. Otherwise it'll give DateTimeParseException
For anyone who landed here with this error, like I did:
Unable to obtain LocalDateTime from TemporalAccessor: {HourOfAmPm=0, MinuteOfHour=0}
It came from a the following line:
LocalDateTime.parse(date, DateTimeFormatter.ofPattern("M/d/yy h:mm"));
It turned out that it was because I was using a 12hr Hour pattern on a 0 hour, instead of a 24hr pattern.
Changing the hour to 24hr pattern by using a capital H fixes it:
LocalDateTime.parse(date, DateTimeFormatter.ofPattern("M/d/yy H:mm"));
This is a really unclear and unhelpful error message. After much trial and error I found that LocalDateTime will give the above error if you do not attempt to parse a time. By using LocalDate instead, it works without erroring.
This is poorly documented and the related exception is very unhelpful.
Expanding on retrography's answer..: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseStrict()
.appendPattern("uuuuMMdd")
.toFormatter()
.withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);
(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)
If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime. You can only convert it to a LocalDate, because the string only represent the year,month and date components it would be the correct thing to do.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06
Anyway you can convert this to LocalDateTime.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
You do not need to define a DateTimeFormatter
You do not need to define a DateTimeFormatter to parse the given date string. You can use the OOTB (Out-Of-The-Box), DateTimeFormatter.BASIC_ISO_DATE to parse it.
Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("20140218", DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(date);
// In case you need an instance of LocalDateTime
LocalDateTime ldt = date.atTime(LocalTime.MIN);
System.out.println(ldt);
}
}
Output:
2014-02-18
2014-02-18T00:00
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time. Check this answer and this answer to learn how to use java.time API with JDBC.
DateTimeFormatter format = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
.toFormatter();
Works for me
In cases where you simply want to take a format (whether or not it has time) and want to parse to a LocalDateTime, you can do the following.
LocalDateTime parseDateTime(String dateTime, DateTimeFormatter fmt) {
return fmt.parse(dateTime, t -> {
LocalDate date = t.query(TemporalQueries.localDate());
LocalTime time = t.query(TemporalQueries.localTime());
return LocalDateTime.of(date, time != null ? time : LocalTime.MIDNIGHT);
});
}
I needed this because I was getting the date/time pattern as a parameter for a custom Spark UDF.
This works fine
public class DateDemo {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm");
String date = "16-08-2018 12:10";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println("VALUE="+localDate);
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
LocalDateTime parse = LocalDateTime.parse(date, formatter1);
System.out.println("VALUE1="+parse);
}
}
output:
VALUE=2018-08-16
VALUE1=2018-08-16T12:10
Try this one:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
LocalDate fromLocalDate = LocalDate.parse(fromdstrong textate, dateTimeFormatter);
You can add any format you want. That works for me!
I arrived at this problem because my input string didn't have a year in it:
input string: Tuesday, June 8 at 10:00 PM
formatter: DateTimeFormatter.ofPattern("EEEE, MMMM d 'at' h:mm a", Locale.US);
I knew the year so I just appended it to get:
input string: Tuesday, June 8 at 6:30 PM 2021
formatter: DateTimeFormatter.ofPattern("EEEE, MMMM d 'at' h:mm a uuuu", Locale.US);

Categories

Resources