在服务器中获取正确的默认值(DateTime)



i从用户那里获得几个参数,在一些样板代码后,我获得了这样的URL:

http://localhost:58756/api/Shippers/GetShippers?page=1&date=1/1/01%2012:00:00%20AM&parx=y&and more parameters...

date=1/1/01%2012:00:00%20AM的零件是这样的:

DateTime date=default(DateTime); 

这给出了1/1/01 12:00:00 AM,即Jan 1st of year 0001

我发送请求,该方法在WebAPI服务中被击中,但是日期值被解析为:1/1/01 2001

我知道我可以使用Nullable DateTime或将参数作为格式化日期ToString("mm/dd/yyyy")等发送。

但是,如果我无法控制客户端发送的内容,而我离开DateTime参数呢?我将如何区分服务器中的2001年1月1日和1月1日0001?

解析两位数的一年时,.NET将使用当前文化日历的Twodigityearmax属性。默认情况下,大多数文化中使用的Gregorian日历将具有2029的值,这意味着两个数字涵盖的100年范围是从19302029

您可以通过将当前文化设置为 custom 文化,该文化对此属性具有不同的价值。

// clone the current calendar and change the range
Calendar cal = (Calendar) CultureInfo.CurrentCulture.Calendar.Clone();
cal.TwoDigitYearMax = 2099;  // changes the range to be 2000-2099 
// clone the culture, set the calendar, and make the new culture active
CultureInfo culture = (CultureInfo) CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.Calendar = cal;
Thread.CurrentThread.CurrentCulture = culture;
// now all date parsing will use the new setting

yy自定义格式规范的文档中,有一个更详细的示例,如果从字符串手动解析,则可以使用该示例。但是,当解析代码进一步堆叠时,将使用相同的方法。

至于克里斯在评论中指出的那样,只有您才能确定。

如果您获得了一年的2位数字,则无法弄清楚它们是指1901,2001,9001还是0001。Y2K错误的原因是当天的一件大事。

我有3个基本规则用于使用Datatimes:

  1. 始终存储,检索和传输UTC值。您不想在麻烦中添加时区。
  2. 避免存储,检索或传输作为文本/字符串。如果有适当的数据类型,请使用它。
  3. 在您无法满足点2的情况下,选择固定文化格式并在所有端点上编码的字符串。您不想添加疯狂的麻烦。

自然而然的文化格式应携带一年中的所有数字。因为否则我们有像您这样的问题。

最新更新