【问题标题】:Check if a string is in a specific date format检查字符串是否为特定日期格式
【发布时间】:2018-06-29 23:14:17
【问题描述】:

您好,我收到一个日期格式为 yyyy-MM-dd 的字符串,但我想将其与格式 dd-MM-yyyy 进行比较,以防万一不一样,当然不一样,我想转换它,对我来说问题不是转换,而是比较两种格式...... 所以我想可能是这样的

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);
}

【问题讨论】:

  • 是的,它是一个字符串@RufusL
  • 这里有多少种格式有问题?就是你提到的那两个

标签: c# date xamarin.forms format


【解决方案1】:

您可以通过拨打TryParseExact 来解决这个问题:

public static DateTime ParseDate(string input)
{
    DateTime result;

    if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;
    if (DateTime.TryParseExact(input, "dd-MM-yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out result)) return result;

    throw new FormatException();
}

快速测试一下:

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.

Sample code on DotNetFiddle

【讨论】:

  • 令人难以置信的先生,真的解决了我的问题。感谢您的宝贵时间。
【解决方案2】:

您是否尝试过查看正则表达式之类的内容?

我找到了这个> (([1-2][0-9])|([1-9])|(3[0-1]))/((1[0-2])| ([1-9]))/[0-9]{4}

与 21/03/1995 匹配

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多