java SimpleDateFormat 解析为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14217044/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:30:08  来源:igfitidea点击:

SimpleDateFormat parse to Date

javadate

提问by faszynski

I have field in class Test:

我在课堂测试中有字段:

private Date date;

Code in main:

主要代码:

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date now = new Date();
Test test = new Test();
test.setDate(sdf.parse(now.toString()));

But I have error:

但我有错误:

java.text.ParseException: Unparseable date: "Tue Jan 08 14:10:23 GMT 2013"
    at java.text.DateFormat.parse(Unknown Source)

How Can I parse today date to sava

我如何将今天的日期解析为 sava

回答by Fortega

now.toString()is not a good way to represent a date as a string, because it uses a 'default' format. To represent a date to a string, you can use the format(Date date)method of SimpleDateFormat:

now.toString()不是将日期表示为字符串的好方法,因为它使用“默认”格式。要将日期表示为字符串,您可以使用以下format(Date date)方法SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date now = new Date();

String dateAsString = sdf.format(date); //"08.01.2013"
Date dateFromString = sdf.parse(dateAsString);