Why DateTime.TryParseExact is not working? - c#

I am reading date from Excel and stored it in a variable In_Date,
formats with which the date is to be compared is stored in Valid_Date_Formats
In_Date = "08/01/2020 00:00:00"
Valid_Date_Formats is an array which stores multiple date formats.
I am checking the format in if condition but it always fails.
If(DateTime.TryParseExact(In_Date, Valid_Date_Formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
DateTime_PlaceHolder))
What am I doing wrong here.

The input string has the following format: dd/MM/yyyy HH:mm:ss, which is missing from Valid_Date_Formats. (I'm assuming the 08 here is the day, because all your other formats start with the date part.)
The following returns the correct date:
DateTime.ParseExact("08/01/2020 00:00:00", new[] { "dd/MM/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.None)
In response to your comment: I'm not aware of a built-in method that would tell you which exact format string was used. If you really need to find out, I guess you could traverse the formats until you find a match:
string[] formats = new[] { "dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss" };
string input = "08/01/2020 00:00:00";
string usedFormat = null;
DateTime date;
foreach (string format in formats)
{
if (DateTime.TryParseExact(input, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
usedFormat = format;
break;
}
}

Related

Parse DayTime from 2 formats

I want to parse the date a user puts in. He is allowed to either use the format DD.MM.YYYY or DDMMYYYY.
Unfortunately everything I tried hasn´t worked
DateTime date = new DateTime();
string[] dateFormat = new string[] { "dd.mm.yyyy", "ddmmyyyy" };
string userInput = "30.10.2000" // or "30102000"
date = DateTime.ParseExact(date, dateFormat, null);
"String was not recognized as a valid DateTime" is the exception. I am from Austria but can´t find a culture code that is working.
Thanks
Try this:
DateTime date = DateTime.MinValue;
string[] dateFormats = { "dd.MM.yyyy", "ddMMyyyy" };
string userInput = "30.10.2000"; // or "30102000"
bool isValid = DateTime.TryParseExact(userInput, dateFormats, null, DateTimeStyles.None, out date);
Console.WriteLine($"{date:O}"); // prints date in ISO format
If date is parsed correctly then isValid will be set to true.
It is yyyy for 4 digit years and dd for 2 digit days. It is case-sensitive. You also neglected to pass the dateFormat array into ParseExact, so it will attempt to only do that single format.

convert date string coming in two different formats YYYYMMDD and DDMMYYYY to date in c#

Tried the below but it only takes care of one format
string date = "20100102";
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
Instead of
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd",
CultureInfo.InvariantCulture);
...try:
var dateString = "20100102";
var formats = new String[]{"yyyyMMdd",
"ddMMyyyy"};
DateTime dateValue;
if (DateTime.TryParseExact(dateString, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
Console.WriteLine ("Success");
MSDN has this to say on DateTime.TryParseExact:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information, and style. The format of the string representation must match at least one of the specified formats exactly. The method returns a value that indicates whether the conversion succeeded.
Tell me more
DateTime.TryParseExact

DateTime.Parse False positives with string containing dotted separated numbers

I'm parsing datetimes from a text read from SQL Server using DateTime.Parse.
String like these:
5.4.1
1.1.4
12.1.13
were identified as dates, while they are not.
I can't use DateTime.TryParseExact(), since I have to load data in different formats:
dd/mm/yy
dd/mm/yyyy
dd MMM YYYY
dd-mm-yyyy
dd.mm.yyyy
How can I parse dates according to those formats, while ignoring values like shown above?
If we use the dates you have specified you can reach a result with the code below.
See also https://msdn.microsoft.com/en-us/library/h9b85w22(v=vs.110).aspx since it is very well explained.
string[] formats= {"dd/MM/yy","dd/MM/yyyy","dd MMM YYYY","dd-MM-yyyy","dd.MM.yyyy","dd.M.yy","d.M.y"};
string[] dateStrings = {"5.4.1","1.1.4","12.1.13"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new System.Globalization.CultureInfo("en-US"),
System.Globalization.DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
This code will result in:
Converted '5.4.1' to 1/5/2001 12:04:00 AM.
Converted '1.1.4' to 1/1/2004 12:01:00 AM.
Converted '12.1.13' to 1/12/2013 12:01:00 AM.
Please notice the cultureinfo! This can give different outputs according to it's setting. For example: month and date can be switched!
Ps. You can immediately try this working snippet on http://csharppad.com/.
You can let dates be parsed according to your expected formats. Just pass the (fixed, mm != MM) formats to TryParseExact():
string[] formats = { "dd/MM/yy", "dd/MM/yyyy", "dd MMM YYYY", "dd-MM-yyyy", "dd.MM.yyyy" };
string[] dateStrings = { "5.4.1", "1.1.4", "12.1.13", "23.02.2016" };
foreach (var dateString in dateStrings)
{
DateTime parsedDate;
if (DateTime.TryParseExact(dateString, formats, null, DateTimeStyles.None, out parsedDate))
{
Console.WriteLine("{0} was parsed as a valid DateTime: {1}", dateString, parsedDate);
}
else
{
Console.WriteLine("{0} was not parsed as a valid DateTime.", dateString);
}
}

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

Check if a string is a valid date using DateTime.TryParse

I am using DateTime.TryParse() function to check if a particular string is a valid datetime not depending on any cultures.
To my surprise , the function returns true for even strings like "1-1", "1/1" .etc.
How can I solve this problem?
Update:
Does it mean, if I want to check if a particular string is valid datetime, I need a huge array of formats?? There will be different combinations , I believe.
Even there are lots of date separator ( '.' , '/' , '-', etc..) depending on the culture, it will be difficult for me to define an array of format to check against .
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution?
So, if the value includes any parts of time, it should return true too.
I could NOT be able to define a array of format.
If you want your dates to conform a particular format or formats then use DateTime.TryParseExact otherwise that is the default behaviour of DateTime.TryParse
DateTime.TryParse
This method tries to ignore unrecognized data, if possible, and
fills in missing month, day, and year information with the current
date. If s contains only a date and no time, this method assumes the
time is 12:00 midnight. If s includes a date component with a
two-digit year, it is converted to a year in the current culture's
current calendar based on the value of the Calendar.TwoDigitYearMax
property. Any leading, inner, or trailing white space character in s
is ignored.
If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:
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.
Use DateTime.TryParseExact() if you want to match against a specific date format
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
{
Console.WriteLine(dateTime);
}
else
{
Console.WriteLine("Not a date");
}
[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
string[] formats = { "MM/dd/yyyy" };
DateTime parsedDateTime;
return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
DateTimeStyles.None, out parsedDateTime);
}
Simply specify the date time formats that you wish to accept in the array named formats.
So this question has been answered but to me the code used is not simple enough or complete. To me this bit here is what I was looking for and possibly some other people will like this as well.
string dateString = "198101";
if (DateTime.TryParse(dateString, out DateTime Temp) == true)
{
//do stuff
}
The output is stored in Temp and not needed afterwards, datestring is the input string to be tested.
An alternative is to create a method to validate that the text is of Date type.
public bool IsDateTime(string date)
{
if (string.IsNullOrEmpty(date)) return false;
return DateTime.TryParse(date, out DateTime dateTime);
}
Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution?
So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.
When I was in a similar situation, here is what I did:
Gather all the formats my system is expected to support.
Looked at what is common or can be generalize.
Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
I created REGEX to cover as many format as possible.
For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.
This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple
was really helpful both for understanding as well as validation the syntax for each format.
My 2 cents if it helps....
Try using
DateTime.ParseExact(
txtPaymentSummaryBeginDate.Text.Trim(),
"MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture
);
It throws an exception if the input string is not in proper format, so in the catch section you can return false;

Categories