I have an application that runs on both C# .Net and Java. Two entirely separate but identical code bases. The problem Im having is formatting date and numbers.
For example: A user running the .Net variant is inputting a date and a format string. The 26th of April 1986 is 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 said XML file and looks at the date. I want them to look the same.
Whats the best approach here? There doesnt seem to be a one-to-one mapping between Java and .Nets format strings. Should I limit the possible formats to a selection I know I can represent fully in both .Net and Java?
I would strongly recommend not to write any parser and writer yourself, but to rely on existing libraries and standards. As you want to write/read to/from an XML file I would strongly recommend using the standard for date-times there: ISO 8601.
Java:
You could use Joda Time, a library that supports the ISO 8601. The format
weekDateTimeNoMillis(see doc) provides just everything you would need if you want to keep the possibility of eventually storing time, too:date(see doc) may be the right thing, if you dont ever want to store time info. It is of the formatyyyy-MM-dd(notice: if you perform a string sort algorithm it will sort it correctly by date)C#:
The .net framework already provides a ISO 8601 writer and parser:
DateTime.UtcNow.ToString("s")will write the correct formatyyyy-MM-ddTHH:mm:ss.You see: you just have to decide for a format (only date, datetime or datetime with timezone) and use the respective tools in both languages and everything will go fine. If you dont specify the format exactly, strange things could happen: you cannot recognize
10-09-08without knowing its format, is it:You/the parser just cant know.