如何验证是否有“日期和时间"?字符串只有时间吗? [英] How to validate if a "date and time" string only has a time?

查看:112
本文介绍了如何验证是否有“日期和时间"?字符串只有时间吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串变量,用于存储完整日期或部分日期:

I have a single string variable that stores what could be a full date or a partial date:

1)完整日期:2010年12月12日上午12:33

1) Full Date: 12/12/2010 12:33 AM

2)部分日期:12:33 AM(没有日期字段仅是时间)

2) Partial Date: 12:33 AM (no date field only time)

我正在尝试找出解析字符串以找出字符串是否缺少日期字符串的最佳方法.原因是,在我的代码中,如果缺少日期,我将在字符串后附加一个默认日期(例如1/1/1900).请记住,时间可能有多种格式.

I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.

更新-我对这个问题的特殊回答.

Update - My particular answer to this problem.

正如所有帖子"都指出的那样,对于这个问题有多种答案,这最终是我所使用的,希望它能对其他人有所帮助*:

As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:

public DateTime ProcessDateAndTime(string dateString)
{
    string dateAndTimeString = dateString;

    string[] timeFormats = new string[]
    {
        "hh:mm tt", "hh:mm:ss tt",
        "h:mm tt", "h:mm:ss tt", 
        "HH:mm:ss", "HH:mm", "H:mm"
    };
    // check to see if the date string has a time only
    DateTime dateTimeTemp;
    if (DateTime.TryParseExact(dateString, timeFormats,
        CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
    {
        // setting date to 01/01/1900
        dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
    }

    return DateTime.Parse(dateAndTimeString);
}

*注意:此方法基于以下假设:您的应用程序中仅使用了特定数量的时间格式,并确保传入了正确格式的日期和时间,或仅传入了时间字符串(删除垃圾文本的验证).

*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).

推荐答案

您可以使用 DateTime.TryParseExact .

这篇关于如何验证是否有“日期和时间"?字符串只有时间吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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