为什么我的日期解析返回一个奇怪的日期?

时间:2013-08-07 13:35:46

标签: java date

以下是我正在使用的代码:

String string = "08/07/2013".replace('/', '-');
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);

为什么日期返回:“Wen Jan 3 00:00:00 EST 14”?它完全不是我告诉它使用的日期格式。

编辑:我需要这种格式,因为我使用的数据库需要这种格式。

3 个答案:

答案 0 :(得分:4)

用于解析日期字符串的格式与之不匹配。您对yyyy使用08

使用以下格式:

new SimpleDateFormat("dd-MM-yyyy")

为什么要用/替换-?您只能为原始字符串构建模式:

String string = "08/07/2013"
Date date = new SimpleDateFormat("dd/MM/yyyy").parse(string);

如果您希望日期字符串采用yyyy-MM-dd格式,那么您可以使用DateFormat#format(Date)方法格式化date

String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);

另见:

答案 1 :(得分:1)

使用字符串指定某些简单日期格式时,例如“yyyy-MM-dd”,您必须以相同的格式提供日期以获取日期对象,例如。 “1991-07-24”。

String mydate = "1991/07/24";
Date formattedDate = new SimpleDateFormat("yyyy/MM/dd").parse(mydate);

现在如果你想以任何其他格式转换它,你可以通过将这个日期对象格式化为相关格式来实现。

String dateInOtherFormat = new SimpleDateFormat("dd-MMM-yyyy").format(formatteddate);

并且dateInOtherFormat的输出将是...... 24-JUL-1991。

答案 2 :(得分:0)

好的我的建议是愚蠢的,但如果你需要这种格式,试试这个

String[] arr = "08/07/2013".split("/");
String newString = arr[2]+"-"+arr[1]+"-"arr[0];
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(newString);

注意如果原始字符串的格式为“MM / dd / YYYY”,请使用此:

String newString = arr[2]+"-"+arr[0]+"-"arr[1];