GetDateFormat()在1601年1月1日之前的日期失败



我正在尝试使用Windows GetDateFormat API函数格式化日期:

nResult = GetDateFormat(
      localeId,   //0x409 for en-US, or LOCALE_USER_DEFAULT if you're not testing
      0,          //flags
      dt,         //a SYSTEMTIME structure
      "M/d/yyyy", //the format we require
      null,       //the output buffer to contain string (null for now while we get the length)
      0);         //the length of the output buffer (zero while we get the length)

现在我们给它一个日期/时间:

SYSTEMTIME dt;
dt.wYear = 1600;
dt.wMonth = 12;
dt.wDay = 31;

在这种情况下,nResult返回零:

如果不成功,函数将返回0。为了获得扩展的错误信息,应用程序可以调用GetLastError,它可以返回以下错误代码之一:

  • ERROR_insuccessient_BUFFER。提供的缓冲区大小不够大,或者未正确设置为NULL
  • ERROR_INVALID_FLAGS。为标志提供的值无效
  • ERROR_INVALID_PARAMETER。任何参数值都无效

然而,如果我在一天后返回日期:

SYSTEMTIME dt;
dt.wYear = 1601;
dt.wMonth = 1;
dt.wDay = 1;

然后它就起作用了。

我做错了什么?如何设置日期格式?

例如基督的出生日期:

12/25/0000

或者宇宙开始的日期:

-10/22/4004 6:00 PM

或者凯撒去世的日期:

-3/15/44

奖励阅读

  • 全部排序:GetDateFormat基于格里高利
  • GetDateFormatEx函数

这实际上是对SystemTime的限制。

...year/month/day/hour/minute/second/milliseconds value since 1 January 1601 00:00:00 UT... to 31 December 30827 23:59:59.999

我花了一些时间研究如何绕过这个限制,但由于GetDateFormat()需要SystemTime,你可能不得不咬紧牙关写自己的format()方法。

SYSTEMTIME结构仅在1601年到30827年期间有效,因为在Windows计算机中,系统时间是从1.1.1601 00:00开始的运行间隔计算的。看见维基百科文章。

最新更新