【发布时间】:2012-03-05 08:42:39
【问题描述】:
我正在尝试将一个字符串解析为yyyy-MM-dd 格式,并将一个字符串解析为yyyy-MM-dd HH:mm:ss。
我正在使用SimpleDateFormat。
我之前成功地使用了相同的方法,但现在出了点问题。我得到标准格式的日期,即Tue Mar 05 00:00:00 GMT+05:30 2012(对于yyyy-MM-dd)和Mon Mar 05 13:01:35 GMT+05:30 2012(对于yyyy-MM-dd HH:mm:ss),因为我需要它们分别是2012-03-05和2012-03-05 13:01:35。
这就是我的工作:
Date today = new Date();
SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
today = tsdf.parse(tsdf.format(new Date()));
} catch(Exception e) {
System.out.println("Error occurred"+ e.getMessage());
}
System.out.println(today);
与
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
// I recieve a string in this format here (refers to 5 march 2012).
myDate = sdf.parse('2012-03-05');
System.out.println(myDate);
} catch(Exception e) {
System.out.println("Error occurred "+ e.getMessage());
}
【问题讨论】:
-
您遇到了什么错误?有堆栈跟踪吗?或者你得到日期的格式是什么?
-
'2012-03-05' 应该是 "2012-03-05"
-
请显示异常堆栈跟踪(由 e.printStackTrace() 生成)
-
第二个例子是编译时错误——应该是
sdf.parse("2012-03-05") -
@TrueDub:没有错误。只不过是格式错误的日期。
标签: java simpledateformat java.util.date