Date format strings in .Net and Java
I have an application that runs in both C # .Net and Java . Two completely different but identical codebases. The problem I'm having is date and number formatting.
For example: a user using the .Net variant enters a date and a format string. On April 26, 1986 formatted 1986-04-26. The actual date, along with the format string, is serialized to an XML file. Later, another user running the Java variant opens the specified XML file and looks at the date. I want them to look the same.
What's the best approach here? There seems to be no one-to-one mapping between Java and .Nets format strings. Should I restrict the possible formats to choices that I know I can fully represent in .NET and Java?
a source to share
I would strongly recommend not writing a parser and writer yourself, but relying on existing libraries and standards. Since you want to write / read to / from an XML file, I highly recommend using the standard for dates: there is ISO 8601 .
Java:
You can use Joda Time , a library that supports ISO 8601. The format weekDateTimeNoMillis
(see doc ) provides just what you need if you want to keep the ability to store time over time as well:
- date
- Time
- Time zone (either "Z" for UTC, or +/- HH: MM for another time zone).
date
(see doc ) might be correct if you never want to store time information. This is the format yyyy-MM-dd
(note: if you follow the string sorting algorithm, it will sort it correctly by date)
FROM#:
The .net framework already provides a script and ISO 8601 parser: DateTime.UtcNow.ToString("s")
will write the correct format yyyy-MM-ddTHH:mm:ss
.
You see: you just need to choose a format (only date, date or time or time with time zone) and use the appropriate tools in both languages, and you will be fine. If you don't specify the format for sure, strange things can happen: you cannot recognize 10-09-08
without knowing its format if it is:
- August 9, 2010
- September 8, 2010
- September 10, 2008
- October 9, 2008
- ...?
You / the parser just don't know.
a source to share
Use a standard format. Since XML defines the date format itself, you are exactly that. See http://www.w3schools.com/Schema/schema_dtypes_date.asp for details . The date will look like 2010-12-24 and the date will look like 2010-12-24T23: 59.
And since Java and .NET have their own date format classes, you just have to decide to use them. However, there is no default date format, if you are using the Java DateFormat class, the date will be printed using the locale of the detected platform. And since this is known to be mutable, you still have to define the format yourself.
a source to share