加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何以HHMMSS格式执行c#时间验证

发布时间:2020-12-15 23:57:15 所属栏目:百科 来源:网络整理
导读:即使我以正确的格式传递日期,此代码的输出也将始终为false.请帮助我… 这里传递的2个参数是时间和格式,即(“HHMMSS”格式). static bool ValidateTime(string time,string format) { try { //time = time.Replace(":",""); System.Globalization.DateTimeFor
即使我以正确的格式传递日期,此代码的输出也将始终为false.请帮助我…
这里传递的2个参数是时间和格式,即(“HHMMSS”格式).

static bool ValidateTime(string time,string format)
    {
        try
        {
            //time = time.Replace(":","");
            System.Globalization.DateTimeFormatInfo tinfo = new System.Globalization.DateTimeFormatInfo();

            tinfo.LongTimePattern = format;

            DateTime dt = DateTime.ParseExact(time,"format",tinfo);
            if (dt.Hour != null)
            {

            }
            return true;
        }
        catch (Exception e)
        {

            return false;
        }
    }

解决方法

static bool ValidateTime(string time,string format)
{
    DateTime outTime;
    return DateTime.TryParseExact(time,format,CultureInfo.InvariantCulture,DateTimeStyles.None,out outTime);
}

请记住,您应该使用“HHmmss”格式字符串来验证24小时的时间.

Custom Date and Time Format Strings (MSDN)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读