我有一个字符串
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(太平洋标准时间)。
我有一个字符串
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(太平洋标准时间)。
你基本上有效地将日期字符串格式转换为日期对象。如果你在那个时候打印输出它,你将得到标准的日期格式化输出。为了在此之后进行格式化,你需要使用指定的格式将其转换回日期对象(先前已经指定)。
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();
}
MM
而不是mm
。 - Buhake Sindi"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
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 表示。
简洁版:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
添加一个try/catch块来捕获ParseException,确保格式是有效的日期。
var startDate = "06/27/2007";
startDate = new Date(startDate);
console.log(startDate);
Date(String)
构造函数已被弃用并可能在未来完全被移除。 - Mr. Lance E Sloan