问题
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);
}
回答1:
You can solve this with a couple calls to 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();
}
Give it a quick test:
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 );
}
}
Output:
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:
have you tried to see something like a Regular expression?
i found this one > (([1-2][0-9])|([1-9])|(3[0-1]))/((1[0-2])|([1-9]))/[0-9]{4}
matches with 21/03/1995
来源:https://stackoverflow.com/questions/51110408/check-if-a-string-is-in-a-specific-date-format