【发布时间】:2014-02-13 04:33:57
【问题描述】:
我有 GetDateTimeOffset(string latitude, string longitude, string dateTime) Web 服务,它确定给定 Lat/Long 和本地 DateTime 的时间偏移。
我们当前的客户端网页使用 DateTimePicker 插件http://trentrichardson.com/examples/timepicker/。我们使用默认的日期格式和格式时间部分作为“h:mm:ss TT Z”,因此我们传递给服务器的字符串看起来像“01/22/2014 12:09:00 AM -05:00”。但我正在考虑让我们的 Web 服务更通用,所以它应该允许传入的 dateTime 字符串格式。
现在我正在使用 BCL http://goo.gl/s9Kypx 以次优方式解析 DateTime 字符串(用户输入)。
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) { }
}
问题:
- a) 上述代码是否是以灵活的“宽恕”方式将用户输入解析为 DateTime 的正确 BCL 方法?
- b) 将 dateTime 字符串解析为 LocalDateTime(Noda Time 类)的好方法是什么?
我想我应该使用
- http://goo.gl/a2wYco 获取系统在野田时间的 LocalDateTime
- LocalDateTimePattern.Parse(String) 并且可能是 Jon Skeet 在http://goo.gl/F8k51c 描述的方法,用于解析各种格式。但是要使用哪些模式才能使其真正灵活?
【问题讨论】: