String to joda LocalDate in format of “dd-MMM-yy”

后端 未结 1 598
甜味超标
甜味超标 2021-01-16 00:36

I am using JAXB and joda time 2.2. to backup the data from Mysql to XML and restore it back. in my Table I have a Date attribute in format of \"16-Mar-05\". I successfully s

1条回答
  •  不思量自难忘°
    2021-01-16 01:17

    So I took your code and ran it and it works fine for me...

    The problem, I think, you're having is that you're expecting a LocalDate object to maintain the format that you original parsed the object with, this is not how LocalDate works.

    LocalDate is a representation of date or period in time, it is not a format.

    LocalDate has a toString method which can be used to dump the value of the object, it, this is a internal format used by the object to provide a human readable representation.

    To format the date, you need to use some kind of formater, that will take the pattern you want and a date value and return a String

    For example, the following code...

    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    String date = "16-Mar-05";
    
    DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yy");
    LocalDate localDate2 = dtf.parseLocalDate(date);
    System.out.println(localDate2 + "/" + dtf.print(localDate2));
    
    //second way
    LocalDate localDate3 = LocalDate.parse(date, DateTimeFormat.forPattern("dd-MMM-yy"));
    System.out.println(localDate3 + "/" + dtf.print(localDate3));
    
    //third way
    DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("dd-MMM-yy");
    DateTime dateTime = FORMATTER.parseDateTime(date);
    LocalDate localDate4 = dateTime.toLocalDate();
    System.out.println(localDate4 + "/" + FORMATTER.print(localDate4));
    

    Produced...

    2005-03-16/16-Mar-05
    2005-03-16/16-Mar-05
    2005-03-16/16-Mar-05
    

    Before you get upset about this, this is how Java Date works as well.

    0 讨论(0)
提交回复
热议问题