简体   繁体   English

DateTime.TryParseExact C#有效格式和解析

[英]DateTime.TryParseExact C# valid format and parsing

Came across with a problem of pasing format. 遇到了格式化的问题。

if (!DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateOn))
{
     return false;
}
else if (!DateTime.TryParseExact(timeString, "hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out timeOn))
{
     return false;
}

return SaveWorkshop(id, name, dateOn, timeOn, capacity, description, duration, isCancelled);

Using Bootstrap Datetimepicker, it does takes a strings from textboxes in format 使用Bootstrap Datetimepicker,它确实从格式化的文本框中获取字符串

dateString = 11/28/2015 and timeString = 6:46 AM dateString = 11/28/2015,timeString = 6:46 AM

But in the result I do have false and is parsing default date. 但是在结果中我确实有假并且正在解析默认日期。 What could be the problem? 可能是什么问题呢?

For your timeString , you need to use h instead of hh specifier. 对于timeString ,您需要使用h而不是hh说明符。

hh specifier is needs a leading zero for single digits like 06 . hh说明符需要像06这样的单个数字的前导零 You need to use h specifier instead. 您需要使用h说明符

That's why your second DateTime.TryParseExact returns false and timeOn will be it's default value. 这就是为什么你的第二个DateTime.TryParseExact返回falsetimeOn将是它的默认值。

If I'm not mistaken, "hh" requires a two-digit hour, which you don't have. 如果我没弄错的话,“......”需要两位数的小时,而你却没有。 Use "h" for non-zero-padded values. 使用“h”表示非零填充值。

Further, your parsing of the time returns today's date at Midnight added the TimeSpan from parsing timeString . 此外,您对时间的解析返回今天的午夜日期,从解析timeString添加了TimeSpan。

Thus, to cut off today's date, do something like this: 因此,要切断今天的日期,请执行以下操作:

// snip ..
DateTime datetimeOn = dateOn.Add(timeOn.TimeOfDay);
return SaveWorkshop(id, name, datetimeOn, capacity, description, duration, isCancelled);

or, of course, modify SaveWorkshop to create datetimeOn internally. 或者,当然,修改SaveWorkshop以在内部创建datetimeOn

Edit 编辑

Also, you could parse in one go: 此外,您可以一次解析:

DateTime datetimeOn;
DateTime.TryParseExact(dateString + timeString, "MM/dd/yyyyh:mm tt", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out datetimeOn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM