从 C# 中的字符串检查日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19019718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking Date format from a string in C#
提问by User1204501
I want to check whether a string
contains dates such as 1/01/2000
and 10/01/2000
in dd/MM/yyyy
format.
我要检查是否string
包含日期等1/01/2000
,并10/01/2000
在 dd/MM/yyyy
格式。
So far I have tried this.
到目前为止,我已经尝试过这个。
DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate);
But how can I check if that format is correct to throw an exception
?
但是我如何检查该格式是否正确throw an exception
?
采纳答案by Nadeem_MK
string inputString = "2000-02-02";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
String.Format("{0:d/MM/yyyy}", dDate);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
回答by Damith
you can use DateTime.ParseExact
with the format string
您可以DateTime.ParseExact
与格式字符串一起使用
DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);
Above will throw an exception if the given string not in given format.
如果给定的字符串不是给定的格式,上面将抛出异常。
use DateTime.TryParseExact
if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.
使用DateTime.TryParseExact
,如果你不需要例外格式不正确的情况下做的,但你可以检查方法的返回值,以确定是否解析值的成功与否。
回答by Ajay
Try this
尝试这个
DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate);
see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
请参阅此链接了解更多信息。http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
回答by KrishnaDhungana
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
我认为解决方案之一是使用 DateTime.ParseExact 或 DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
回答by Silverstar
you could always try:
你总是可以尝试:
Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");
r.isMatch(inputString);
this will check that the string is in the format "02/02/2002" you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy
这将检查字符串的格式是否为“02/02/2002”,如果您想确保它是一个有效的日期,例如 dd/mm/yyyy,您可能需要多一点
回答by Yasel
Use an array of valid dates format, check docs:
使用一组有效的日期格式,检查文档:
string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);
if(isValidFormat)
{
string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
// maybe throw an Exception
}
回答by Fabián Plaza Arnau
https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx
https://msdn.microsoft.com/es-es/library/h9b85w22(v=vs.110).aspx
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
回答by R.S.K
You can use below IsValidDate():
您可以在以下 IsValidDate() 中使用:
public static bool IsValidDate(string value, string[] dateFormats)
{
DateTime tempDate;
bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
if (validDate)
return true;
else
return false;
}
And you can pass in the value and date formats. For example:
您可以传入值和日期格式。例如:
var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}
if (IsValidDate(data, dateFormats))
{
//Do something
}
else
{
//Do something else
}