I have GetDateTimeOffset(string latitude, string longitude, string dateTime) web service which determines Time Offset given Lat/Long and local DateTime.
Our current client web page uses DateTimePicker plugin http://trentrichardson.com/examples/timepicker/. We use the default date formatting and format time part as 'h:mm:ss TT Z' so a string we pass to a server looks like '01/22/2014 12:09:00 AM -05:00'. But I'm thinking about making our web service more generic, so it should be forgiving for a format of dateTime string passed in.
Right now I'm parsing DateTime string (user input) in an sub-optimal way using BCL http://goo.gl/s9Kypx.
var tmpDateTime = new DateTimeOffset(DateTime.Now).DateTime;
if (!String.IsNullOrEmpty(dateTime))
{
try
{
// Note: Looks stupid? I need to throw away TimeZone Offset specified in dateTime string (if any).
// Funny thing is that calling DateTime.Parse(dateTime) would automatically modify DateTime for its value in a system timezone.
tmpDateTime = DateTimeOffset.Parse(dateTime).DateTime;
}
catch (Exception) { }
}
Questions:
- a) Is the above code a proper BCL method of parsing user input into DateTime in flexible "forgiving" way?
- b) What would be a good and "forgiving" way of parsing dateTime string into LocalDateTime (Noda Time class)?
I suppose I should use
- http://goo.gl/a2wYco for getting the system's LocalDateTime in Noda Time
- LocalDateTimePattern.Parse(String) and probably the approach described by Jon Skeet here http://goo.gl/F8k51c for ability to parse various formats. But which patterns to use to make it really flexible?
If you need to parse that specific pattern, then you can do that
DateTimeOffset.TryParseExact
, or with NodaTime code to parse from that input:But going back to your statement:
That is not a good idea. If you are creating a web service, you should be very explicit about the format that you are using. Preferably, it should not be this format that you showed here, but instead should be the ISO-8601 extended format such as
2014-01-22T12:09:00-05:00