使用DateTime.ParseExact()的时间解析问题 [英] Time parsing Issue using DateTime.ParseExact()
问题描述
我将时间值存储为字符串,格式为HH:mm
I have a Time Value stored as string with the format HH:mm
我使用以下代码将其与今日日期"解析为日期
I used the following code to parse it as date with Today Date
DateTime.ParseExact("09:00","HH:mm",New System.Globalization.CultureInfi("En-GB"))
结果为2017-03-15 09:00:00
从另一台计算机运行此代码时,我得到以下结果:1899-12-31 09:00:00
When Running this Code From another machine i get the following Result: 1899-12-31 09:00:00
我将代码替换为以下内容
I replaced my code to the following
DateTime.ParseExact(DateTime.Now.ToString("yyyy-MM-dd") & " 09:00","yyyy-MM-dd HH:mm",New System.Globalization.CultureInfi("En-GB"))
它可以正常工作,但是我仍然想知道为什么每个系统都将日期解析为不同的值?
推荐答案
DateTime.ParseExact
中缺少的Year/Month/Day的默认值
从.NET源代码:
Default values for missing Year/Month/Day in DateTime.ParseExact
From .NET source code:
下表描述了获取默认值的行为
当缺少某些年/月/日值时.
"X"表示该值存在. -"表示缺少值.
The following table describes the behaviors of getting the default value
when a certain year/month/day values are missing.
An "X" means that the value exists. And "--" means that value is missing.
Year Month Day => ResultYear ResultMonth ResultDay Note
X X X Parsed year Parsed month Parsed day
X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
-- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
-- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
-- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
-- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
这篇关于使用DateTime.ParseExact()的时间解析问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!