将12小时时间字符串转换为DateTime对象 [英] Convert 12hr Time String to DateTime object

查看:92
本文介绍了将12小时时间字符串转换为DateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在处理一些原始的XML,它有一个时间元素,价值如此

So I'm processing some raw XML and it has a time element with a value as such

10:30 PM

或相反

10:30 AM

等等

日期推定为今天...

The Date is presumed to be today...

如果我要使用DateTime.TryParse;任何人都愿意帮助制定一个FormatProvider来完成这项工作?

If I was to use DateTime.TryParse; would anyone be willing to help out crafting a FormatProvider would to do the job?

如果有其他人有一个更聪明的解决方案,它不一定是DateTime.TryParse。

It doesn't have to be DateTime.TryParse if anyone else has a smarter solution..

推荐答案

您不需要使用自定义格式提供程序 - 您只需要指定一个自定义格式字符串 AM / PM指示符说明符(tt)

You don't need to use a custom format provider - you just need to specify a custom format string with the AM/PM designator specifier ("tt"):

DateTime result;
if (DateTime.TryParseExact(text, "hh:mmtt", CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out result))
{
    Console.WriteLine("Parsed to: {0}", result);
}

这篇关于将12小时时间字符串转换为DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆