Parse DateTime string into Noda Time LocalDateTime in a forgiving way?

限于喜欢 提交于 2019-12-24 08:49:43

问题


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?

回答1:


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



来源:https://stackoverflow.com/questions/21294437/parse-datetime-string-into-noda-time-localdatetime-in-a-forgiving-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!