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开发者_C百科 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
- Time
- Timezone (either a 'Z' for UTC, or +/-HH:MM for a different time zone).
date
(see doc) may be the right thing, if you dont ever want to store time info. It is of the format yyyy-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 format yyyy-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-08
without knowing its format, is it:
- 9th Aug 2010
- 8th Sep 2010
- 10th Sep 2008
- 9th Oct 2008
- ... ?
You/the parser just cant know.
Use a Standard Format. Since XML defines a Date format itself, you exactly this. See http://www.w3schools.com/Schema/schema_dtypes_date.asp for more info. A Date would look like 2010-12-24, and a datetime like 2010-12-24T23:59.
And since Java and .NET both have their own date format classes, you just should decide to use one. There is no "default" date format, however, if you use the Java DateFormat class, the date will be printed using the detected platform locale. And since this is known to be changable, you have to speficify the format yourself anyway.
精彩评论