display Java.util.Date in a specific format

后端 未结 10 1682
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 08:56

I have the following scenario :

SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");
System.out.println(dateFormat.parse(\"31/05/2011\"));


        
相关标签:
10条回答
  • 2020-11-22 09:11

    java.time

    Here’s the modern answer.

        DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
        DateTimeFormatter displayFormatter = DateTimeFormatter
                .ofLocalizedDate(FormatStyle.SHORT)
                .withLocale(Locale.forLanguageTag("zh-SG"));
    
        String dateString = "31/05/2011";
        LocalDate date = LocalDate.parse(dateString, sourceFormatter);
        System.out.println(date.format(displayFormatter));
    

    Output from this snippet is:

    31/05/11

    See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.

    If you need the exact format you gave, just use the source formatter as display formatter too:

        System.out.println(date.format(sourceFormatter));
    

    31/05/2011

    I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.

    To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.

    Link: Oracle tutorial: Date Time explaining how to use java.time.

    0 讨论(0)
  • 2020-11-22 09:13

    How about:

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
    
    > 31/05/2011
    
    0 讨论(0)
  • 2020-11-22 09:14

    You can use simple date format in Java using the code below

    SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
    Date newDate = new Date();
    String expectedDate= simpledatafo.format(newDate);
    
    0 讨论(0)
  • 2020-11-22 09:16

    You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).

    0 讨论(0)
  • 2020-11-22 09:20

    I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code

    BasicImplementation

    0 讨论(0)
  • 2020-11-22 09:21

    Use the SimpleDateFormat.format

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date date = new Date();
    String sDate= sdf.format(date);
    
    0 讨论(0)
提交回复
热议问题