使用DateTime.ParseExact只获取时间(不含当日)不含、当日、时间、DateTime

2023-09-04 09:07:46 作者:奉旨泡妞%

我得到意想不到的结果,当我使用DateTime.ParseExact。 下面是我的测试code:

I get unexpected results when I use DateTime.ParseExact. Here's my test code:

Dim MinVal As DateTime = #12:00:01 AM#
Dim MaxVal As DateTime = #11:59:59 PM#
Dim TooBig1, Equal1 As Boolean
Dim TooBig2, Equal2 As Boolean

Dim dt1 As DateTime = #12:00:01 AM#
Dim dt2 As DateTime = DateTime.ParseExact("12:00:01 AM", "hh:mm:ss tt", Globalization.DateTimeFormatInfo.InvariantInfo)

TooBig1 = (dt1.CompareTo(MaxVal) > 0)
Equal1 = (dt1.CompareTo(MinVal) = 0)

TooBig2 = (dt2.CompareTo(MaxVal) > 0)
Equal2 = (dt2.CompareTo(MinVal) = 0)

结果是罚款DT1:

The result is fine for dt1:

它显示了在调试器#12:00:上午01点#(不含当日) TooBig1为False Equal1为True

但结果是(错?)出乎意料的DT2:

But the result is (wrong?) unexpected for dt2:

它显示了在调试器的第9 /二千零一十一分之三十○上午十二时零零分01秒# TooBig2为True Equal2为False

看起来这是因为这一天是ParseExact系统的加入,即使我只指定格式的时间。

It looks like it's because the day is systematically added by ParseExact even though I only specify the time in the format.

我的问题是:我如何读取刚与DateTime.ParseExact时间

My question is: How can I read just the time with DateTime.ParseExact?

推荐答案

文档规定:

如果格式定义时间,没有日期元素和分析操作成功,得到的日期时间值有一个日期 DateTime.Now.Date

If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

如果你想,没有日期的时间,你可以使用:

If you want a time with no date, you can use:

var parsedDate = DateTime.ParseExact(...);
var timeOnly = parsedDate - parsedDate.Date;
 
精彩推荐