Hot questions for Using Joda-Time in illegalargumentexception

Top Java Programmings / Joda-Time / illegalargumentexception

Question:

I am trying to parse ISO 8601 duration of 1 month to Joda Duration object. Can you please help me why this line of code

 Duration duration = Duration.parse("P1M");

throws

java.lang.IllegalArgumentException: Invalid format: "P1M"
at org.joda.time.convert.StringConverter.getDurationMillis(StringConverter.java:111)
at org.joda.time.base.BaseDuration.<init>(BaseDuration.java:105)
at org.joda.time.Duration.<init>(Duration.java:209)
at org.joda.time.Duration.parse(Duration.java:59)

Answer:

In this case, it should be a Period not a Duration as it is one month long so try this instead:

Period period = Period.parse("P1M");

Indeed a Duration needs to be expressed in an exact amount of milliseconds and as a month cannot be exactly expressed in milliseconds as it changes from one month to another it cannot be a Duration.

More details about Period and Duration here

Question:

this Code is throwing the "invalid format" or "malformed" Exception:

Code:

strDate = "21/10/2015 12:00:00 AM";
format = "dd/MM/yyyy hh:mm:ss a";

DateTime.parse(strDate, DateTimeFormat.forPattern(format)).toDate();

Exception:

java.lang.IllegalArgumentException: Invalid format: "21/10/2015 12:00:00 AM"
is malformed at "AM"

What's wrong?

I'm ussing joda-time:2.8.1

(I already searched and i think this is the correct pattern for that strDate)


Answer:

The text of the AM/PM marker may be different to that of your default locale. You could do

Date date = 
  DateTime.parse(strDate, DateTimeFormat.forPattern(format).withLocale(Locale.US)).toDate();

Question:

Before to post, i search this format in previous questions but i dont found it

Here is the simple code that i want to try :

String YYYYMMDD_HHMMSS = "yyyy/MM/dd HH:mm:ss";
DateTimeFormatter yyyyMMddHHmmssFormatter = DateTimeFormat.forPattern(YYYYMMDD_HHMMSS); 
DateTime fromDate = DateTime.parse("2019-01-17 11:01:15", yyyyMMddHHmmssFormatter);

I got this error :

java.lang.IllegalArgumentException: Invalid format: "2019-01-17 11:01:15" is malformed at "-01-17 11:01:15"

I think, i must change something in the string format ?

Thank's for your help


Answer:

You shoud use format yyyy-MM-dd HH:mm:ss for input 2019-01-17 11:01:15, yyyy/MM/dd HH:mm:ss works when the input like 2019/01/17 11:01:15.

Update

You need two format to convet:

DateTimeFormatter inputFormat = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss"); 
DateTime fromDate = DateTime.parse("2019-01-17 11:01:15", inputFormat);
System.out.println(outputFormat.print(fromDate));

Question:


Answer:

Here :

Timestamp.valueOf(String.valueOf(LocalDateTime.now() [...])

You are converting a LocalDateTime (from joda time) to a String and expect Timestamp.valueOf (from java.sql.Timestamp) to be able to parse it but they don't use the same date format.

You should convert the LocalDateTime to a timestamp (i.e. number of milliseconds) then compare from this point.

Example :

long timestamp = LocalDateTime.now().minusMonths(12).toDateTime().getMillis()

EDIT :

Then you can create a new Timestamp from this long value and compare using Timestamp.before(Timestamp) :

if(person.getBirthday().before(new Timestamp(timestamp)) {
  [...]
}

Question:

I'm writing some code to store metadata from uploaded images in the database. One of those fields is the photo Capture Date. The API I'm using returns the Capture Date in the String format

Sat Nov 01 20:08:07 UTC 2014

However, Joda Time throws an IllegalArgumentException when creating a DateTime or LocalDateTime. Conversely, java.util.Date accepts the string formatting and creates a Date object with no issue.

One solution is to do

Date tempDate = new Date("Sat Nov 01 20:08:07 UTC 2014");
DateTime captureDate = new DateTime(tempDate);

but this requires creating two separate objects to persist one. Given the string format above, is it possible to convince JodaTime to create a DateTime object without an intermediary Date initialization?


Answer:

The Joda Time DateTime and LocalDate constructors which take Object have documentation including:

The String formats are described by ISODateTimeFormat.dateTimeParser().

The text you're providing is not in an ISO format.

Instead, you should create a DateTimeFormatter for the format you're using, e.g. via DateTimeFormat.forPattern, specifying the locale, time zone etc. (It's not clear from your example whether it's always going to be in UTC, or whether you need time zone handling.)

For example:

private static final DateTimeFormatter DATETIME_PARSER =
    DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'UTC' yyyy")
        .withLocale(Locale.US)
        .withZoneUTC();

...

DateTime dateTime = DATETIME_PARSER.parseDateTime(text);

Question:

The front end is sending the date with an invalid time format and I get this exception:

Caused by: java.lang.IllegalArgumentException: Invalid format: "2018-08-24T��:��:��" is malformed at "��:��:��" at org.joda.time.format.DateTimeParserBucket.doParseMillis(DateTimeParserBucket.java:187) at org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:826) at org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65) at org.joda.time.base.BaseDateTime.(BaseDateTime.java:173) at org.joda.time.DateTime.(DateTime.java:257)

Basically I want to check if the timestamp has any malformed data. If yes, I want to set it to 0. For example the datetime is 2018-08-24T��:��:�� I want to set it to 2018-08-24T00:00:00


Answer:

You are already half-way there.

try {
 .. your code that parses the FED input
} catch ( IllegalArgumentException e) {
 .. do further checking

Meaning: that exception is already giving you, well, an exception, when you received bad input from your source. In that case, you could a simply substring() or regex check on the incoming string. And if it goes "4digits dash 2 digits dash 2 digits" ... then you got a date, and can create a corresponding object manually, and fill in the time values to all 0 for example.

Question:

I use Joda Time Framework. In My function i do this:

...
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(DateTime.now().toString());
...

i have this error:

java.lang.IllegalArgumentException: Invalid format: "2016-03-11T11:38:22.666+01:00" is malformed at "16-03-11T11:38:22.666+01:00"

What's wrong ..?

Update:

I use the @user2004685 code:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime newTime = formatter.parseDateTime(new Date().toString());
Date startDate =  newTime.toDate();
newTime = formatter.parseDateTime(DateTime.now().plusMonths(6).toString());
Date endDate = newTime.toDate();

i have this new error:

java.lang.IllegalArgumentException: Invalid format: "Fri Mar 11 12:09:36 CET 2016"


Answer:

You should try this:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

Question:

I have the foloowing snippet which convert milli-seconds to a Date according to a format. I am using Joda-time 2.3.

final Long currentMs = new DateTime().getMillis());
DateTimeFormatter currentMsTimeFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dt = currentMsTimeFormat.parseDateTime(String.valueOf(currentMs));
System.out.println(dt.toString());

When I run this program I get the following error:

java.lang.IllegalArgumentException: Invalid format: "1455711149006" is malformed at "9006"

where 1455711149006 is the value of currentMs.


Answer:

There is a constructor for DateTime that takes milliseconds since EPOCH. So you probably want:

new DateTime(currentMs);

Question:

I'm receiving a crash from a single device when it tries to parse a date

class DateTimeUtils {
  public static DateTime toDateTime(String value) {
     return DateTime.parse(value, DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z"));
  }
}

Stack trace

Caused by java.lang.IllegalArgumentException: Invalid format: "Mon, 29 Oct 2018 15:17:19 +0000"
   at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
   at org.joda.time.DateTime.parse(DateTime.java:160)
   at com.example.app.DateTimeUtils.toDateTime(DateTimeUtils.java:58)

Any ideas?


Answer:

The problem was solved by setting the locale same as locale of the date to be parsed (in this case US). The device on which crash was happening had different one.

DateTime.parse(value, DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z").withLocale(Locale.US));

Question:

This code:

DateTimeParser[] parsers = { DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss zzz").getParser(),
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").getParser(), DateTimeFormat.forPattern("dd/MM/yyyy HH:mm").getParser(),
DateTimeFormat.forPattern("HH:mm").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();

Session session;
DateTime dTime = null;
Calendar calendar;

try{
    if (completedTime != null && !completedTime.equalsIgnoreCase("")){
        LocalDateTime jt = LocalDateTime.parse(completedTime, formatter);
        LocalDateTime dt;
        LocalDateTime retDate;

produces the error:

java.lang.IllegalArgumentException: Invalid format: "09/05/2015 04:00:00 GDT" is malformed at " GDT" at the LocalDateTime jt = LocalDateTime.parse(completedTime, formatter); line

I can't for the life of me work out why it is failing. I am pretty sure it is something simple, but I haven't spotted it.


Answer:

You may want to refer to this thread (or one of the many others like it). My best advice would be to try cutting to only one "z" in your parser.