Reputation: 21440
As per this C# code from Mircrosoft there is a standard date format such as this:
// R: Sun, 15 Jun 2008 21:15:07 GMT
My C# code uses "r" like so:
webRequest.Date.ToUniversalTime().ToString("r")
How can I create a standard date format like this in 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.
Upvotes: 0
Views: 1496
Reputation: 1503489
How can I create a standard date format like this in Java?
Look at the documentation for the r
format:
The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss '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
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):
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. Personally I'd go with an ISO-8601 format instead, e.g.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Upvotes: 4