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

140

我有一个字符串

String startDate = "06/27/2007";

现在我需要获取一个日期对象。我的DateObject应该与startDate的值相同。

我是这样做的:

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

但输出的格式为

2007年1月27日00:06:00(太平洋标准时间)。


2
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = null; try { startDate = dateFormat.parse("03/04/1975"); String formattedDate = dateFormat.format(startDate); System.out.println("After format Date is=" + formattedDate); // } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } - user4423251
5个回答

192

你基本上有效地将日期字符串格式转换为日期对象。如果你在那个时候打印输出它,你将得到标准的日期格式化输出。为了在此之后进行格式化,你需要使用指定的格式将其转换回日期对象(先前已经指定)。

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();
}

3
您在代码中使用了“format”方法以按所需格式显示字符串。但这仍然是一个字符串。您能否获得与代码中的startDateString相同格式的日期对象? - user755043
2
我不理解这个问题。日期对象的默认“格式”如下:Jan 27 00:06:00 PST 2007。如果你想改变它,你需要使用DateFormat类...... 日期只是一个对象,从技术上讲,它甚至没有“格式”,它只是存储有关日期的数据......在其上覆盖toString方法可能会给您不同的输出,但这就是DateFormat的作用,以维护所有日期对象的完整性和一致性。 - citizen conn
1
另外,如果您要在应用程序中始终使用此类型的格式,您可以对日期对象进行子类化,并具有带有辅助方法的CustomDate,以返回所需的格式类型和可能更多的自定义信息。 - citizen conn
1
你的月份格式字符串是错误的。它必须是MM而不是mm - Buhake Sindi
1
"找不到符号 DateFormat。请下次记得包含导入模块..." - Mathieu Turcotte
显示剩余4条评论

20

"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

如果我打印startDate,仍然会看到它的格式为Mon May 23 00:00:00 PDT 2011。 - user755043

9
    try 
    {  
      String datestr="06/27/2007";
      DateFormat formatter; 
      Date date; 
      formatter = new SimpleDateFormat("MM/dd/yyyy");
      date = (Date)formatter.parse(datestr);  
    } 
    catch (Exception e)
    {}

月份用 MM 表示,分钟用 mm 表示。


1
如果你在代码中打印日期,它的格式可能是像Mon May 23 00:00:00 PDT 2011这样的。但我需要一个类似于我的字符串06/27/2007的日期对象。 - user755043
噢,好的,理解这段代码只会将您的字符串转换为有效的Java日期对象。它无法影响打印格式。它只是另一个日期对象。 - mihsathe

6

简洁版:

String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);  

添加一个try/catch块来捕获ParseException,确保格式是有效的日期。


-7
var startDate = "06/27/2007";
startDate = new Date(startDate);

console.log(startDate);

2
那目前可行,但Date(String)构造函数已被弃用并可能在未来完全被移除。 - Mr. Lance E Sloan
2
这个问题是针对Java的,而你发布的代码是JavaScript。Java和JavaScript不是同一种语言。 - Lucky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接