문제

I am currently using the joda dateTime Api in my application. I am using the following code to parse multiple formats of dates into one single format. I am having trouble though when the format does not have a year. currently it sets the year as "2000".

Is there a way to set the year to a default if it is missing?

private static final DateTimeParser[] parsers = {
  DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z").getParser(),
  DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").getParser(),
  DateTimeFormat.forPattern("[dd/MMM/yyyy:HH:mm:ss Z]").getParser(),
  DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").getParser(),
  DateTimeFormat.forPattern("MMM-dd HH:mm:ss,SSS").getParser()
 };

 public static DateTime ConvertDate(String timestamp) {

   DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();

   DateTime date = formatter.parseDateTime(timestamp);
   return date;
}

example: Mar-07 13:59:13,219

becomes 2000-03-07T12:59:13.219-07:00

what I want :

example: Mar-07 13:59:13,219

becomes (currentyear)-03-07T12:59:13.219-07:00

도움이 되었습니까?

해결책

You can use withDefaultYear():

public static DateTime convertDate(String timestamp) {

  int stdYear = 1970; // example for new default year

  DateTimeFormatter formatter = 
    new DateTimeFormatterBuilder().append(null, parsers).toFormatter()
    .withDefaultYear(stdYear);

  return formatter.parseDateTime(timestamp);
}

다른 팁

Since Joda 2.0 the default year is 2000 so that Feb 29 could be parsed correctly, check this.

Not sure if you can change that (check this with pivotYear), but as a bypass solution I would add current year to my timestamp if there wasn't any.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top