如何在java中格式化日期字符串?

sad*_*ter 36 java datetime date simpledateformat

嗨,我有以下字符串:2012-05-20T09:00:00.000Z,我想将其格式化为20/05/2012,9am

如何在java中这样做?

谢谢

Kep*_*pil 78

如果您正在寻找特定案例的解决方案,那将是:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);
Run Code Online (Sandbox Code Playgroud)

  • 日期必须是java.util.Date,使用java.sql.Date它不起作用(只是一个注释) (5认同)

Jig*_*shi 31

SimpleDateFormatparse() StringDate,然后format() DateString


小智 5

package newpckg;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)