简单的日期格式为两个不同的字符串提供相同的日期
我编写了一个小方法,在给定字符串时返回日期对象。方法如下所示:
public Date getDateObjectFromString(String dateAsString)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date tempDate = null;
try
{
tempDate = sdf.parse(dateAsString);
}
catch(ParseException pe)
{
//do some error reporting here
}
return tempDate;
}
一切正常,但我遇到了一些我想澄清的问题。当我将两个不同的字符串传递给此方法时,它在读取调试器中的值时返回相同的日期。我传递的两个字符串是:
2011-07-21T19:44:00.000-0400
2011-07-21T19:44:00.000-04:00
正如您所看到的,这两个字符串几乎相同,当我在调试器中查看这些新创建的日期的变量输出时,它显示了两个字符串完全相同的日期/时间。那么,如果调试器显示相同的日期,第二个字符串(04:00)中的冒号有什么区别吗?我应该担心还是可以继续进行而不会在以后出现任何奇怪的错误?
I have written a small method to return a date object when given a string. The method is as shown below:
public Date getDateObjectFromString(String dateAsString)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date tempDate = null;
try
{
tempDate = sdf.parse(dateAsString);
}
catch(ParseException pe)
{
//do some error reporting here
}
return tempDate;
}
Everything is working ok, but I've run into something that I'd like to clarify. When I pass two different strings to this method it is returning the same date when reading the value in the debugger. The two strings I am passing are:
2011-07-21T19:44:00.000-0400
2011-07-21T19:44:00.000-04:00
As you can see these two strings are nearly identical, and when I look at the variable output for these newly created dates in the debugger, it shows the exact same date/time for either string. So, does the colon in the second string (at 04:00) make any difference if the debugger is showing the same date? Should I worry or can I proceed without any weird bugs popping up later on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是维基百科关于 ISO 8601 的说法 “与 UTC 的时间偏移”
因此基本上您使用的两种格式都是允许的,您不必担心。
This is what Wikipedia says about ISO 8601 'Time offsets from UTC'
So basically both formats you are using are permitted and you shouldn't worry about it.
SimpleDateFormat 的 Android 文档提到它们使用 RFC 822 时区。当我访问 SimpleDateFormat 的 JavaDocs(Android 试图用此类来模仿)时,我看到 此注释关于 RFC 822 时区:
以下是一般时区的注释:
在一般时区的定义中,您会注意到它们使用“:”。
这意味着您的两个字符串虽然不同,但将被解析为相同的时间。
The Android docs for SimpleDateFormat mention that they use RFC 822 timezones. When I went to the JavaDocs for SimpleDateFormat, which is what Android is attempting to mimic with this class, I see this note about RFC 822 timezones:
And here is the note for general time zones:
In the definition for the general time zones, you will notice they use a ':'.
This means that your two strings, while different, will be parsed to the same time.
第二个字符串中的冒号没有什么区别;您可以毫无恐惧地继续前进。
The colon in the second string doesn't make a difference; you can proceed without fear.