如何为带有可选时间部分的通用日期格式定义DateTime解析格式? [英] How to define DateTime parse format for general date format with optional time part?

查看:68
本文介绍了如何为带有可选时间部分的通用日期格式定义DateTime解析格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的 DateTime 格式以解析具有通用日期格式("G")的字符串中的日期以及可选的时间部分("d")?

我可以有两种日期类型:

  1. "2012年12月13日下午6:30:00"
  2. "2013年3月29日"

如何统一解析它们?现在,我正在尝试使用"G" 格式进行解析,然后如果不使用"d" 格式进行解析.

解决方案

如果您的 LongTimePattern 具有 h )和 M/dd/yyyy (我假设您的 DateTime.TryParse(String,out DateTime)方法可以解决所有问题.

  string s =";DateTime dt;如果(DateTime.TryParse(s,out dt)){//您的字符串已成功解析.} 

如果这些格式不是 CurrentCulture 的标准日期和时间格式,请使用

当您解析具有 "/"的字符串时,请当心自定义格式说明符.它具有用当前区域性或指定的区域性日期分隔符替换我的特殊含义.这意味着,如果您的 CurrentCulture DateSeparator 属性不是/,如果您的字符串和格式相同,则解析操作也会失败甚至.

What is the right DateTime format to parse a date from string in general date format ("G") with optional time part ("d")?

I can have two types of dates:

  1. "12/13/2012 6:30:00 PM"
  2. "3/29/2013"

How to parse them in unified way? Right now I'm trying to parse with "G" format and then if it not parsed with "d" format.

解决方案

If your CurrentCulture supports MM/dd/yyyy h:mm:ss tt (I assume your LongTimePattern has h) and M/dd/yyyy (I assume your ShortDatePattern has M) as standard date and time format, using DateTime.TryParse(String, out DateTime) method can solve all your problems.

string s = "";
DateTime dt;
if (DateTime.TryParse(s, out dt))
{
    // Your string parsed successfully.
}

If these formats doesn't standard date and time format for your CurrentCulture, using DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload can be the best choice because it takes formats part as a string array. That means, you can provide multiple formats and your string will be parsed with first successful match.

string s = "";
string[] formats = { "MM/dd/yyyy h:mm:ss tt", "M/dd/yyyy" };
DateTime dt;
if (DateTime.TryParseExact(s, formats, CultureInfo.CurrentCulture,
                           DateTimeStyles.None, out dt))
{
    // Your string parsed with one of speficied format.
}

Be careful when you parse string that have "/" custom format specifier. It has a special meaning of replace me with current culture or specified culture date separator. That means if your CurrentCulture's DateSeparator property is not /, your parsing operation will fail even if your string and formats are the same format.

这篇关于如何为带有可选时间部分的通用日期格式定义DateTime解析格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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