gpt4 book ai didi

c# - 检查字符串是否采用特定日期格式

转载 作者:行者123 更新时间:2023-12-02 03:33:34 25 4
gpt4 key购买 nike

您好,我收到了一个日期格式为 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);
}

最佳答案

您可以通过几次调用 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

关于c# - 检查字符串是否采用特定日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51110408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com