如何让MonthCalendar控件在PM中显示DateTime?

How to have MonthCalendar control display DateTime in PM?

我在 C# 应用程序中使用 MonthCalendar 控件并希望在下午显示日期时间,即 PM

我可以通过创建 2-DateTime 变量,即 DateTime 开始,在 AM 中成功地将它获取到 return DateTime ;和日期时间结束;

如果我像这样分配这些变量:

start = MonthCalendar.SelectionRange.Start.AddHours(10);
end = MonthCalendar.SelectionRange.End.AddHours(10).AddMinutes(30);

然后我可以设置范围从10:00 AM10:30 AM。这工作正常,但我还需要在 PM 中写回数据库时间。

如何使用上面的语法在下午显示 DateTime,例如 1:00 下午到 1:30 下午?

我注意到日历控件有一个 TimeOfDay 功能,但是在使用谷歌搜索并在 MonthCalendar.SelectionRange.Start.AddHours 下搜索后,我找不到任何相关内容。也搜索了SOF,但没有得出任何答案。

让我试着弄清楚一些事情;

  • 不能有一个像1:00 PM1:30 PM这样的DateTime实例。 Datetime 实例没有 any 隐式格式。它只有日期和时间值。当您获得它们的 textual (字符串)表示时,格式化概念 only 适用。这就是为什么你可以为它们设置字符串变量。
  • DateTime 值作为字符串保存到数据库中 通常 不是一个好主意。一般来说,您应该将 DateTime 值而不是字符串保存到您的数据库中,并在例如 UI 中显示它们时生成它们的字符串表示形式。

How to get those formats based on your DateTime values?

简单。首先,将 1313,5(等于 13 小时 30 分钟)小时添加到 StartEnd 中,并使用 .ToString() method with h:mm tt custom format as a first parameter and a culture that uses AM and PM in AMDesignator and PMDesignator and has GregorianCalendar as Calendar property like InvariantCulture 作为第二个参数。

string startStr = MonthCalendar.SelectionRange.Start.AddHours(13)
                               .ToString("h:mm tt", CultureInfo.InvariantCulture);
string endStr = MonthCalendar.SelectionRange.End.AddHours(13,5)
                               .ToString("h:mm tt", CultureInfo.InvariantCulture);

现在你有 1:00 PM amd 1:30 PM 作为字符串变量。