检查字符串是否采用特定的日期格式 [英] Check if a string is in a specific date format

查看:118
本文介绍了检查字符串是否采用特定的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我收到的日期格式为 yyyy-MM-dd 的字符串,但我想将其与 dd-MM-yyyy 格式的字符串进行比较这是不一样的,肯定不是,我想将其转换,对我来说,这不是转换,而是比较两种格式的问题... 所以我想也许是这样的

Hi I'm receiving a string with a date format yyyy-MM-dd , but I want to compare it with a format dd-MM-yyyy in case it is not the same, sure is not, I want to convert it, the problem for me it's not to convert, it's to compare both formats... so I imagine maybe it's something like this

var dt = obj.date; //this a string

if (dt.formatDateorsomethingIguess == "dd/MM/yyyy") //this is the part I'm asking for
{
     usedt(dt);
} 
else 
{
    DateTime dt_format = DateTime.ParseExact(dt.Trim(), "dd-MM-yyyy",
    System.Globalization.CultureInfo.InvariantCulture);
    usedt(dt_format);
}

推荐答案

您可以通过几次调用

快速测试一下

public static void Main()
{
    string[] tests = new string[] { "2018-06-29", "29-06-2018","Invalid" };

    foreach (var t in tests)
    {
        var result = ParseDate(t);
        Console.WriteLine( "Year: {0}  Month: {1}  Day: {2}", result.Year, result.Month, result.Day );
    }
}

输出:

Year: 2018  Month: 6  Day: 29
Year: 2018  Month: 6  Day: 29
Run-time exception (line 18): One of the identified items was in an invalid format.

DotNetFiddle上的示例代码

这篇关于检查字符串是否采用特定的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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