c# - 使用 DateTime 解析时如何知道时间部分是否存在

标签 c# asp.net .net datetime

比如说,我有两个包含日期/时间的字符串,采用任意用户提供的格式,适用于任意文化:

string str1 = "6/19/2013";
string str2 = "6/19/2013 1 am";

我可以通过以下方式解析它们:

DateTime dt1 = DateTime.Parse(str1);
DateTime dt2 = DateTime.Parse(str2);

但我如何知道时间部分是否存在并解析到 DateTime 对象中?

最佳答案

你们怎么看待这样的事情?

public static DateTime ParseDateTimeWithTimeDifferentiation(string str, out bool bOutTimePresent)
{
    //Parse date/time from 'str'
    //'bOutTimePresent' = receives 'true' if time part was present
    DateTime dtRes;

    //Get formats for the current culture
    DateTimeFormatInfo dtfi = CultureInfo.CurrentUICulture.DateTimeFormat;

    DateTimeStyles dts = DateTimeStyles.AllowWhiteSpaces | 
        DateTimeStyles.AssumeLocal;

    //Get all formats
    string[] arrFmts = dtfi.GetAllDateTimePatterns();

    foreach (string strFmt in arrFmts)
    {
        if (DateTime.TryParseExact(str, strFmt, CultureInfo.InvariantCulture, dts, out dtRes))
        {
            //Parsed it!

            //These format codes come from here:
            // http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
            bOutTimePresent = strFmt.IndexOfAny(new char[] { 'H', 'h', 'm', 's', 'f', 'F', 't', 'z' }) != -1;

            return dtRes;
        }
    }

    //As a fall-back, just parse it as-is
    dtRes = DateTime.Parse(str);

    //Assume it has time, as otherwise we'd catch the date-only above
    bOutTimePresent = true;

    return dtRes;
}

关于c# - 使用 DateTime 解析时如何知道时间部分是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17204289/

相关文章:

c# - 在 Entity Framework 中将多个外键设置为主键

c# - 处理 WCF 服务应用程序上的数据库更改

c# - ASP.NET 表卡住 Pane (标题和列)

.net - 我应该如何在这段 winform 代码中使用 IoC?

c# - ASP.NET WebAPI : how to perform a multipart post with file upload using WebApi HttpClient

c# - XmlNode.SelectNodes 返回 0 个节点

asp.net - 如何确定在我的页面上请求的是哪种 css 媒体类型?

iphone - 如何开发多目标移动 Web 应用程序

c# - vsts new repo 有许多平台/语言的 gitignore 选项,但 .net/c# 没有

javascript - 使用 jquery 切换 LinkBut​​ton 的启用/禁用状态