DateFormat does not work?

前端 未结 4 1926
难免孤独
难免孤独 2021-01-22 08:49
String selectedDate = \"2012-\" + createdMonth + \"-\" + createdDay;

SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");

try {
    createdDate = dateFo         


        
相关标签:
4条回答
  • 2021-01-22 08:54

    You seem to think that createdDate, which is a Date object, has the format yyyy-MM-dd. It doesn't. Date objects don't have a format - they just contain a timestamp, just like numbers are just numbers, which don't have a format by themselves.

    A SimpleDateFormat object is used to parse a String into a Date object, or format a Date object into a String.

    If you have a Date object and you want to display the date in a particular format, then convert it to a String with the appropriate format using a SimpleDateFormat object:

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    String text = fmt.format(createdDate);
    System.out.println("Created: " + text);
    

    If you print a Date object without explicitly formatting it, it will be formatted using a default format, which is why you see Thu Mar 08 00:00:00 CST 2012.

    A Date object does not somehow remember what the format was of the String that you parsed it from.

    0 讨论(0)
  • 2021-01-22 09:11

    The parse method returns a java.util.Date and that is the what the Date implementation of toString() returns.

    0 讨论(0)
  • 2021-01-22 09:14

    You need to print as below. Point is that you need to use the formatter object you have created while printing as well.

    System.out.println(dateFormat.format(createdDate));
    
    0 讨论(0)
  • 2021-01-22 09:17

    use dateFormat.format(createdDate)

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