java 如何从字符串值创建日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15760248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create Date object from String value
提问by Hussain Akhtar Wahid 'Ghouri'
When running through the below code I am getting an UNPARSABLE DATE EXCEPTION
.
当运行下面的代码时,我得到一个UNPARSABLE DATE EXCEPTION
.
How do I fix this?
我该如何解决?
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();
}
}
}
回答by PermGenError
You used wrong dateformat for month, also you should use the same delimiter as in your date.
您为月份使用了错误的日期格式,您也应该使用与日期相同的分隔符。
If you date string is of format "2013/01/03"
如果你的日期字符串是格式 "2013/01/03"
use the same delimiter /
for the pattern "yyyy/MM/dd"
/
对模式使用相同的分隔符"yyyy/MM/dd"
If your date string is of format "2013-01-03"
如果您的日期字符串是格式 "2013-01-03"
use the same delimiter '-' in your pattern "yyyy-MM-dd"
在您的模式中使用相同的分隔符“-” "yyyy-MM-dd"
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
should be
应该
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
From SimpleDateFormat Doc
MM---> month in an year
MM---> 一年中的一个月
mm---> minutes in hour
mm---> 分钟
回答by Ankit
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
you are using different pattern than what you are parsing.
您使用的模式与正在解析的模式不同。
either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
or this as String startDateString = "2013/03/26";
将此初始化为DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
或将其初始化为String startDateString = "2013/03/26";
回答by rajesh
MM
instead of mm
MM
代替 mm
-
instead of /
ie yyyy-MM-dd
as you are using -
in date string
-
而不是/
ieyyyy-MM-dd
正如您-
在日期字符串中使用的那样
回答by Nirbhay Mishra
pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")
在 SimpleDateFormat("yyyy-mm-dd") 的构造函数中传递相同的格式字符串
as your string date is "2013-03-26"
因为您的字符串日期是“2013-03-26”
if your date is "2013/03/26" use
如果您的日期是“2013/03/26”,请使用
SimpleDateFormat("yyyy/mm/dd")
SimpleDateFormat("yyyy/mm/dd")