简体   繁体   English

将字符串解析为Date对象

[英]Parsing of string to Date Object

I have string "Tue Nov 12 2010",I want to parse it in java.util.Date object. 我有字符串“Tue Nov 12 2010”,我想在java.util.Date对象中解析它。 I write below code for this 我为此写了下面的代码

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date= format.parse("Tue Nov 12 2010");

It is giving exception like below: 它给出了如下例外情况:

java.text.ParseException: Unparseable date: "Sun Nov 21 2010"

Not getting what is wrong with it??? 没弄到它有什么问题?

您的格式错误 - 如果您指定格式dd/MM/yyyy ,那么您需要提供要以相应格式(!)格式化的字符串,例如21/11/2010

Ofcourse because it is not in format 因为它不是格式的

format for Tue Nov 12 2010 should be EEE MMM dd yyyy Tue Nov 12 2010格式应为EEE MMM dd yyyy

Have a look at docs 看看文档

Learn to read code and use common sense. 学习阅读代码并使用常识。

DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date= format.parse("Tue Nov 12 2010");

This should be blatantly obvious that the format specified doesn't match the string being parsed. 显然,指定的格式与正在解析的字符串不匹配。 They're on adjacent lines, right next to each other. 它们位于相邻的线上,彼此相邻。 It doesn't get more straightforward than that. 它并没有比那更直截了当。

You need to be able to see something like this if you are to be a successful programmer. 如果你想成为一名成功的程序员,你需要能够看到类似的东西。 If you can't see this, how are you ever going to find similar problems when the two lines causing problems aren't even in the same source code file? 如果你看不到这个,那么当导致问题的两行甚至不在同一个源代码文件中时,你怎么会发现类似的问题?

My advice is to take some personal responsibility for learning how to read and debug code. 我的建议是学习如何阅读和调试代码。 Something like this should be a huge red flag right when you type it that the two lines of code don't match up. 当您输入两行代码不匹配时,这样的东西应该是一个巨大的红旗。

The date format you have created 您创建的日期格式
new SimpleDateFormat("dd/MM/yyyy"); 新的SimpleDateFormat(“dd / MM / yyyy”);
Will only parse dates of that form. 只会解析该表单的日期。 Ie 05/10/1989 You'll need to change the format something more appropriate. 即05/10/1989您需要更改更合适的格式。

To parse the date you need to provide correct format. 要解析您需要提供正确格式的日期。 For the sample date give by you the format would be "EEE MMM dd yyyy" 对于您提供的样本日期,格式为"EEE MMM dd yyyy"

You are using the wrong format for the date. 您使用的格式错误。 To parse it according to your string format use "EEE MMM dd yyyy" 要根据您的字符串格式解析它,请使用“EEE MMM dd yyyy”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM