How can I validate a date in different formats - c#

I got a regular expression to valid a date which is as follows
^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
But this will valid if I enter date as follows 20/03/2012 .. With the same I would like to add different validation which can work together for the following
20032012 (ddmmyyyy) 03202012(mmddyyyy)
Can some one help me

Use DateTime.TryParseExact - there is an overload that takes an array of format strings, so you can supply all of the possible formats.
From MSDN - DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime):
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);
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.

Related

Checking Date format from a string in C#

I want to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.
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?
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
}
you can use DateTime.ParseExact with the format string
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.
check Custom Date and Time Format Strings
I think one of the solutions is to use DateTime.ParseExact or DateTime.TryParseExact
DateTime.ParseExact(dateString, format, provider);
source: http://msdn.microsoft.com/en-us/library/w2sa9yss.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);
}
You can use below 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
}
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
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
}
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

Parsing DateTime to Universal Time C#

I have a xml which can return a time in the format (7/23/2013 4:00pm) my question is: How can I explain to DateTime.ParseExact that I'm in the "am" or in the "pm"? I have this piece of code, but it returns me an exception (String can not be parsed)
I alredy placed an example string (7/23/2013 4:00pm) in which I replace "pm" by the empty chain "".
string pattern = "MM/dd/yyyy H:mm 'UTC' zzz";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Thank you very much :)
You can pass an array to cover various formats. I use the following for various time inputs.
var formats = new[]
{
"M/dd/yyyy hh:mm tt",
"M/dd/yyyy hh:mmtt",
"M/dd/yyyy h:mm tt",
"M/dd/yyyy h:mmtt",
"M/dd/yyyy hhtt",
"M/dd/yyyy htt",
"M/dd/yyyy h tt",
"M/dd/yyyy hh tt"
};
var date = "7/23/2013 4:00pm";
DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
H in your pattern expects the time in a 24 style. You need tt (as outlined in the previous answer) AND you must a small h in your pattern:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
You need the tt format:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);

DateTime parsing

I am writing a syslog server that receives syslog messages and stores them in a database.
I am trying to parse the date string received in the message into a DateTime structure.
For the following examples, I'll be using an underscore in place of whitespace for clarity; the actual strings received have spaces.
The string I received is in the format "Jun__7_08:09:10" - please note the two whitespaces between the month and day.
If the day is after the 10th, the strings become "Jun_10_08:09:10" (one whitespace).
If I parse with:
DateTime.ParseExact(Log.Date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture);
it works for strings from the 1st to 9th but throws exception from the 10th forward, and if I parse with one space, it throws an exception on the 1st to 9th (and works from the 10th on).
What is the correct way to parse this string?
Consider using this line:
DateTime.ParseExact(Log.Date,
"MMM d HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces);
Notice that I removed one of the spaces between the month and the day. That's because AllowWhiteSpaces literally means:
Specifies that s may contain leading, inner, and trailing white spaces not defined by format.
Use the DateTime.ParseExact overload that takes an array of format strings:
DateTime.ParseExact(Log.Date,
new [] {"MMM d HH:mm:ss", "MMM d HH:mm:ss"},
CultureInfo.InvariantCulture,
DateTimeStyles.None);
You could remove the extra space first and then parse the string:
DateTime.ParseExact(Log.Date.Replace(" ", " "), "MMM d HH:mm:ss", CultureInfo.InvariantCulture);
DateTime's ParseExect Method has some overloads where you can pass multiple format that could be readed if the earlier one is not working. here a sample for you..
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
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)
{
try {
dateValue = DateTime.ParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
}
}
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
DateTime.ParseExact(date, "MMM d HH:mm:ss", CultureInfo.InvariantCulture,DateTimeStyles.AllowInnerWhite)

How to check whether a string date can be converted to a DateTime or not?

There is a SQL Server 2008 database for which I have to create a management software. The database contains a column named DateOfCreation. The table designer made this column as string and gave freedom to users to add date in any format they want and this was really a silly mistake by him. Now some users added as "24 Jan" or
"Jan 24" or "1991 1 12" and many unknown formats. What I want is that when I fetch this string date, a function should be called that will check the format and return -1 if date is not in correct format else return the converted date in DD/MM/YYYY. So how can I check the format of the date that string date variable is containing?
use DateTime.TryParseExact with your date format, it will return false in case if the date format is different or invalid.
For multiple formats you can specify multiple formats in a string array and then use that in DateTime.TryParseExact something like:
From MSDN - DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime%)
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);
}
DateTime.TryParse could help to some extent. However, you would be dependent on your user using an appropriate date/time format.
public Tuple<bool, DateTime> GetDateTime(string x)
{
DateTime DT = null;
return Tuple.Create((DateTime.TryParse(x, out DT)), DT)
}
may work. I can't guarantee it though.

Parsing dates and times from string in many combinations

I need to parse dates and times from strings. The Problem is that the strings can have any possible format. But I also get the format strings.
So i get:
Date = "9/15/2010"
Time = "16:12:45"
DateFormat = "M/dd/yyyy"
TimeFormat = "h:mm:ss"
TimeZone = "+2:00:00" // +/- and time in TimeFormat
But i have some problems parsing these strings.
I can't parse the time
DateTime.ParseExact("16:12:45","h:mm:ss",null,DateTimeStyles.None);
does not work and causes a FormatException. What is wrong with this call?
If the DateFormat contains slashes, i need to escape them #"M\/dd\/yyyy". Are there any other chars that would need escaping?
Can i parse the whole DateTime in one? Somehting like:
DateTime.ParseExact(Date+' '+Time+' '+TimeZone,DateFormat+' '+TimeFormat+' +'+TimeFormat,null,DateTimeStyles.None);
What is wrong with this call?
The "h:mm:ss" format string expects the hours element to be in 12-hour format (h); The hours in your string are in 24-hour format so you need to use H instead:
DateTime.ParseExact("16:12:45", "H:mm:ss", null, DateTimeStyles.None);
Are there any other chars that would need escaping?
Any literal character in your string that clashes with a format specifier will need to be escaped. For example, / is the date separator but \/ means the literal / character; : is the time separator but \: means the literal : character; y is one of the year specifiers but \y is the literal y character.
Can i parse the whole DateTime in one?
Yes.
How about this?
var #return = (DateTime?)null;
if (source != null)
{
source = source.Trim();
if (source.Length > 0)
{
var fs = new string[]
{
"d MMMM yyyy h:mm tt",
"d MMMM yyyy h:mm:ss tt",
"d MMMM yyyy HH:mm",
"d MMMM yyyy HH:mm:ss",
"d MMMM yyyy",
"d/M/yy h:mm tt",
"d/M/yy h:mm:ss tt",
"d/M/yy HH:mm",
"d/M/yy HH:mm:ss",
"d/M/yy",
"d/M/yyyy HH:mm",
"d/M/yyyy HH:mm:ss",
"d/M/yyyy h:mm:ss tt",
"d/M/yyyy",
"d/M/yyyy h:mm tt",
"d-MMMM-yy HH:mm",
"d-MMMM-yyyy h:mm tt",
"d-MMMM-yyyy h:mm:ss tt",
"d-MMMM-yyyy HH:mm",
"d-MMMM-yyyy HH:mm:ss",
"d-MMMM-yyyy",
"d-MMM-yy",
"d-MMM-yy h:mm tt",
"d-MMM-yy h:mm:ss tt",
"d-MMM-yy HH:mm",
"d-MMM-yy HH:mm:ss",
"d-MMM-yyyy",
"d-M-yy h:mm tt",
"d-M-yy h:mm:ss tt",
"d-M-yy HH:mm",
"d-M-yy HH:mm:ss",
"d-M-yy",
"d-M-yyyy",
"yyyy/M/d h:mm tt",
"yyyy/M/d h:mm:ss tt",
"yyyy/M/d HH:mm",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy-M-d h:mm tt",
"yyyy-M-d h:mm:ss tt",
"yyyy-M-d HH:mm",
"yyyy-M-d HH:mm:ss",
"yyyy-M-d",
"yyyy-MM-ddTHH:mm:ss",
};
#return = DateTime.ParseExact(source, fs,
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None);
}
}
return #return;
Do you know which culture the original string belongs to? If you do you can specify a culture specific DateTimeStyle when calling Parse()
DateTime date = DateTime.Parse("<your specific date>", System.Globalization.CultureInfo.GetCultureInfo("<your culture>").DateTimeFormat);
Create a custom DateTimeFormatInfo and pass that into DateTime.Parse. Like this:
string dateValue = string.Format("{0} {1}", "9/15/2010", "16:12:45");
var customDateTimeFormatInfo = new DateTimeFormatInfo();
customDateTimeFormatInfo.FullDateTimePattern = string.Format("{0} {1}", "M/dd/yyyy", "h:mm:ss");
DateTime dt = DateTime.Parse(dateValue, customDateTimeFormatInfo);
No escaping required and handled your "h:mm:ss" fine with no modification required.

Categories

Resources