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

我有根绳子

String startDate = "06/27/2007";

现在我必须得到 Date 对象。我的 DateObject 应该和 startDate 的值相同。

我就是这么做的

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

但输出是格式化的

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

604384 次浏览

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

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

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

编辑: DateFormat 对象包含日期格式化定义,而不包含 Date 对象,后者仅包含日期而不考虑格式化。 在讨论格式时,我们讨论的是以特定格式创建 Date 的 String 表示形式。看这个例子:

    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
    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。

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


console.log(startDate);

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

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

简明的说法是:

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

为 ParseException 添加 try/catch 块,以确保格式是有效的日期。