Reputation: 1621
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:
I suppose I should use
Upvotes: 1
Views: 3879
Reputation: 241633
If you need to parse that specific pattern, then you can do that DateTimeOffset.TryParseExact
, or with NodaTime code to parse from that input:
var defaultValue = new OffsetDateTime(new LocalDateTime(2000, 1, 1, 0, 0), Offset.Zero);
var pattern = OffsetDateTimePattern.Create("MM/dd/yyyy hh:mm:ss tt o<m>", CultureInfo.InvariantCulture, defaultValue);
var result = pattern.Parse("01/22/2014 12:09:00 AM -05:00");
if (!result.Success)
{
// handle your error
}
OffsetDateTime value = result.Value;
LocalDateTime local = value.LocalDateTime;
But going back to your statement:
But I'm thinking about making our web service more generic, so it should be forgiving for a format of dateTime string passed in.
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
Upvotes: 2