如何将java字符串转换为日期对象

2022-08-31 08:03:33

我有一根绳子

String startDate = "06/27/2007";

现在我必须得到日期对象。我的日期对象应与 startDate 的值相同。

我就是这样做的

DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Date startDate = df.parse(startDate);

但输出是格式的

2007 年 1 月 27 日 00:06:00 PST 2007.


答案 1

您基本上有效地将字符串格式的日期转换为日期对象。如果此时将其打印出来,您将获得标准日期格式输出。为了在此之后格式化它,您需要将其转换回具有指定格式(之前已指定)的日期对象

String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}

答案 2

“mm”表示日期的“分钟”片段。对于“月”部分,请使用“MM”。

因此,请尝试将代码更改为:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
Date startDate = df.parse(startDateString);

编辑:DateFormat 对象包含日期格式设置定义,而不是 Date 对象,后者仅包含日期而不考虑格式设置。在谈论格式设置时,我们谈论的是以特定格式创建日期的字符串表示形式。请参阅此示例:

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

    public class DateTest {

        public static void main(String[] args) throws Exception {
            String startDateString = "06/27/2007";

            // This object can interpret strings representing dates in the format MM/dd/yyyy
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

            // Convert from String to Date
            Date startDate = df.parse(startDateString);

            // Print the date, with the default formatting. 
            // Here, the important thing to note is that the parts of the date 
            // were correctly interpreted, such as day, month, year etc.
            System.out.println("Date, with the default formatting: " + startDate);

            // Once converted to a Date object, you can convert 
            // back to a String using any desired format.
            String startDateString1 = df.format(startDate);
            System.out.println("Date in format MM/dd/yyyy: " + startDateString1);

            // Converting to String again, using an alternative format
            DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy"); 
            String startDateString2 = df2.format(startDate);
            System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
        }
    }

输出:

Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007