java – 如何从String值创建Date对象
作者:互联网
在运行下面的代码时,我得到了一个不可行的日期异常.
我该如何解决?
package dateWork;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCreation {
/**
* @param args
*/
public static void main(String[] args) {
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date startDate=null;
String newDateString = null;
try
{
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
System.out.println(startDate);
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
解决方法:
您在月份中使用了错误的dateformat,也应该使用与日期相同的分隔符.
如果您的日期字符串格式为“2013/01/03”
使用相同的分隔符/用于模式“yyyy / MM / dd”
如果您的日期字符串格式为“2013-01-03”
在你的模式“yyyy-MM-dd”中使用相同的分隔符’ – ‘
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
应该
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
MM —>一年中的一个月
毫米—>小时分钟
标签:java,date-format,simpledateformat,date-formatting 来源: https://codeday.me/bug/20190714/1454941.html