简体   繁体   English

Java日期和标准格式

[英]Java Dates and Standard Formats

As per this C# code from Mircrosoft there is a standard date format such as this: 根据Mircrosoft的C#代码,存在以下标准日期格式:

//       R: Sun, 15 Jun 2008 21:15:07 GMT 

My C# code uses "r" like so: 我的C#代码使用“ r”,如下所示:

webRequest.Date.ToUniversalTime().ToString("r")

How can I create a standard date format like this in Java? 如何在Java中创建这样的标准日期格式?

I have this so far: 到目前为止,我有:

this.timestamp = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());

But, I don't know if I should try to write something that will match it or if there is a better way. 但是,我不知道是否应该尝试编写与之匹配的东西,或者是否有更好的方法。 My fear is that I will make a mistake and certain dates won't work. 我担心我会犯一个错误,并且某些日期无法使用。

How can I create a standard date format like this in Java? 如何在Java中创建这样的标准日期格式?

Look at the documentation for the r format : 查看有关r格式的文档

The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". 自定义格式字符串为“ ddd,dd MMM yyyy HH':​​'mm':'s'GMT'”。 When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture. 使用此标准格式说明符时,格式化或解析操作始终使用不变的区域性。

[...] Therefore, the application must convert the date and time value to UTC before it performs the formatting operation [...]因此,应用程序必须在执行格式化操作之前将日期和时间值转换为UTC

So you translate that custom format string into SimpleDateFormat , *and make sure you specify the time zone (UTC) and locale (US English is close enough to the invariant culture): 因此,您可以将该自定义格式字符串转换为SimpleDateFormat ,*并确保指定时区(UTC)和语言环境(美国英语足够接近不变文化):

DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'",
                                         Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
String text = format.format(date);

That's if you want to match the format from .NET's r format. 那就是如果您想匹配.NET r格式的格式。 Personally I'd go with an ISO-8601 format instead, eg 我个人会使用ISO-8601格式,例如

DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
                                         Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));

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

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