Json LocalDateTIme issue - java

Exception during serialization - message:
Cannot deserialize value of type `java.time.LocalDateTime` from String "2021-05-04T09:06:27-05:00":
Failed to deserialize java.time.LocalDateTime:
(java.time.format.DateTimeParseException) Text '2021-05-04T09:06:27-05:00'
#JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", shape = JsonFormat.Shape.STRING )
#JsonProperty("inprogress_ts")
val inProgressTs: LocalDateTime
Why can't this #JsonFormat pattern parse the String "2021-05-04T09:06:27-05:00"?

It does not work because you are using a non suitable data type / class:
A LocalDateTime does not consider offsets, it simply has none and cannot parse Strings containing an offset.
Your String contains -05:00, which will cause the DateTimeParseException being thrown.
Use a suitable class: An OffsetDateTime instead.

The string your are passing hasnĀ“t got the same format than JsonFormat:
2021-05-04 T 09:06:27 -05:00
yyyy-MM-dd 'T' HH:mm:ss ??????

If you include zone then it should work. I have written a sample extension function in kotlin may help
fun String.convertDateString(): String {
val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH)
val date: Date = dateFormat.parse(this) ?: Date()
val outFormat = SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH)
return outFormat.format(date)
}
Input: "2021-05-04T09:06:27-05:00"
Formatted Response: "May 04, 2021".
Actual date : 2021-05-04T16:06:27.000+0200 (GMT+2:00 time zone)

I have formatted like below and then converted manually
#JsonProperty("event_ts")
val packedCentralTime = eventTs.withZoneSameInstant(ZoneId.of("America/Chicago")).toLocalDateTime()

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

Joda DateTime Invalid format

I'm trying to get the current DateTime with my DateTimeFormat pattern, but i'm getting the exception...
//sets the current date
DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
DateTime now = dtf.parseDateTime(currentDate.toString());
I'm getting this exception, I cannot understand who is giving the malformed format
java.lang.IllegalArgumentException: Invalid format: "2017-01-04T14:24:17.674+01:00" is malformed at "17-01-04T14:24:17.674+01:00"
This line DateTime now = dtf.parseDateTime(currentDate.toString()); isn't correct because you try parse date with default toSring format. You have to parse string which formatted the same way as pattern:
DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
String formatedDate = dtf.print(currentDate);
System.out.println(formatedDate);
DateTime now = dtf.parseDateTime(formatedDate);
System.out.println(now);
You are using the wrong format to parse the date. If you print out the date you are trying to parse after converting it to a String with toString you get:
2017-01-04T14:24:17.674+01:00
This date string does not conform to the pattern dd/MM/YYYY HH:mm. To parse the to a string converted currentDate to a DateTime object again, you have to use the following pattern:
DateTimeFormatter dtf = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ss.SSSZ")
.withLocale(locale);
Parsing with this DateTimeFormatter will get you another instance that represents the same time as the original currentDate.
For more details on the DateTimeFormatter and it's parsing options check out the JavaDoc

DateFormat from ''yyyy-MM-dd" to "dd-MM" using Joda-Time

I have following code:
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM");
LocalDate weekMon = new LocalDate().withWeekOfWeekyear(thisWeek).withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(weekMon.toString());
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
and the output prints the date correctly: 2015-02-02. I'm trying to convert it to European format and ignoring the year as "dd-MM" -> "02-02" but the line:
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
keeps throwing following exception:
java.lang.IllegalArgumentException: Invalid format: "2015-02-02" is malformed at "5-02-02"
What is wrong with the formation in this case ?.
Probably what you need is to print, and not to parse.
In other words:
String dateStr = dtf.print(weekMon);
Notice that with this code:
LocalDate weekFin = dtf.parseLocalDate(weekMon.toString());
you are trying to parse a string in "yyyy-MM-dd" format using a formatter that accepts strings in "dd/MM" format. Hence the exception...

Java: Date Format

I am trying to parse the following string to date
2013-02-01T09:37:20EST
I need to compare it with current date to see it is before or after current date.
Here is what I am doing
Date formatTime(String time) throws exception
{
String format = "yyyy-MM-dd HH:mm:ss z";
DateFormat dateFormat = new SimpleDateFormat(format);
Date expTime = dateFormat.parse(time);
return expTime;
}
I am getting java.text.ParseException: Unparseable date: "2013-02-01T09:37:20EST" (at offset 10)
Thanks.
notice the space before the timezone z and wrap T around quotes 'T'
String format = "yyyy-MM-dd'T'HH:mm:ss z";
The format should be like this: yyyy-MM-dd'T'HH:mm:ssZ
Your input time String does not match your DateFormat pattern. You could use:
String format = "yyyy-MM-dd'T'HH:mm:ssz";
SimpleDateFormat

joda DateTime parser error

I use jodatime to parse date time strings as follows:
public static void main(String[]args){
String s ="16-Jul-2009 05:20:18 PDT";
String patterns = "dd-MMM-yyyy HH:mm:ss z";
DateTimeFormatter fm = DateTimeFormat.forPattern(patterns);
DateTime d=fm.parseDateTime(s);
System.out.println(d);
}
I get
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "16-Jul-2009 05:20:18 PDT" is malformed at "PDT"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:683)
what's wrong? how to parse the timezone properly?
From the DateTimeFormat javadoc:
The pattern syntax is mostly compatible with java.text.SimpleDateFormat - time zone names cannot be parsed and a few more symbols are supported. All ASCII letters are reserved as pattern letters, which are defined as follows:
Your best bet is to fall back to SimpleDateFormat and then construct DateTime based on Date#getTime().
String s = "16-Jul-2009 05:20:18 PDT";
String pattern = "dd-MMM-yyyy HH:mm:ss z";
Date date = new SimpleDateFormat(pattern, Locale.ENGLISH).parse(s);
DateTime d = new DateTime(date.getTime());
System.out.println(d);

Categories

Resources