Why is the DateTime tryparse failing for the date 20140404 - c#

I wrote a simple unit test that fails when trying to parse the date "20140404".
DateTime dt;
DateTime.TryParse("20140404", out dt);
Assert.IsTrue(dt.Year == 2014 && dt.Month == 4 && dt.Day == 4);
Can someone clear this up for me, should I be passing in the expected format?
On my webpage form, I said I want users to enter the format yyyymmdd.

You need to supply the format in DateTime.TryParseExact.
DateTime dt;
DateTime.TryParseExact("20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
You can also validate if the parsing was successful or not
DateTime dt;
if (DateTime.TryParseExact("20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//parsing successfull
}
else
{
//parsing failed
}
TryParse group of methods returns a boolean value indicating if parsing was successful or not. When the parsing fails it returns false instead of raising an exception and the out variables is assigned the default value. That is why your Test is failing, since dt was assigned the default value dt = {01/01/0001 12:00:00 AM}.
Why parsing with TryParse was failing in your case? , because DateTime.Parse and DateTime.TryParse use already defined date formats in DateTimeFormatInfo Class. Your format is not one of them.

You'd need to specify a custom format string and use TryParseExact:
bool success = DateTime.TryParseExact(
"20140404",
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
// Check success
If you're going to ignore the return value, you'd be better off using ParseExact instead of TryParseExact, as you'd get an exception in that case if you feed bad data.

As to why it doesn't work: DateTime.TryParse iterates over the standard formats inside DateTimeFormatInfo and this isn't among the list.
You can verify this by executing
new DateTimeFormatInfo().GetAllDateTimePatterns().ToList().ForEach(Console.WriteLine);
If you don't want to use ParseExact, you can add your own formats to this collection using SetAllDatePatterns().

Related

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

String to Date parsing

I am getting a string and i want to parse that string as date and want to store it in DataTable.
string can be in formats
1- "2014/23/10"
2- "2014-23-10"
{
string st="2014/23/10";
string st="2014-23-10";
}
And attach time with it.
Any idea to make it possible ?
DateTime.ParseExact or DateTime.TryParseExact are appropriate here - both will accept multiple format strings, which is what you need in this case. Make sure you specify the invariant culture so that no culture-specific settings (such as the default calendar) affect the result:
string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd" };
DateTime date;
if (DateTime.TryParseExact(input, formats,
CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Add date to the DataTable
}
else
{
// Handle parse failure. If this really shouldn't happen,
// use DateTime.ParseExact instead
}
If the input is from a user (and is therefore "expected" to be potentially broken, without that indicating an error anywhere in the the system), you should use TryParseExact. If a failure to parse indicates a significant problem which should simply abort the current operation, use ParseExact instead (it throws an exception on failure).
Since both are not standart date and time format, you can use DateTime.ParseExact method like;
string st = "2014/23/10";
string st1 = "2014-23-10";
var date = DateTime.ParseExact(st,
"yyyy/dd/MM", CultureInfo.InvariantCulture);
var date1 = DateTime.ParseExact(st1,
"yyyy-dd-MM", CultureInfo.InvariantCulture);
Output will be;
10/23/2014 12:00:00 AM
10/23/2014 12:00:00 AM
Here a demonstration.
Of course these outputs depends your current culture thread.
If you want to format your DateTime's as a string representation, you can use DateTime.ToString(string) overload which accepts as a string format.
Since you have more than one format, you can use DateTime.TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) overload which is takes your formats as a string array.
var formats = new []{"yyyy-MM-dd", "yyyy/MM/dd"};
DateTime dt;
if(DateTime.TryParseExact(st, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//
}
else
{
//
}
Convert to a DateTime with DateTime.TryParseExact(); or even DateTime.Parse if you need to be flexible. Then you can format it back out however you like!
See: http://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx
Try
DateTime.Parse(st, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Set DateTimeStyles based on your requirement.
Try this:
DateTime.Parse(st);
If It the above line not works for you, then add cultrureInfo below:
DateTime.ParseExact(st,"yyyy/dd/MM", CultureInfo.InvariantCulture);

Convert String to DateTime

I have a string like this:
"20090212"
and I want to convert to valid C# datetime.
Do I need to parse it out because that seems too much work?
You can use DateTime.ParseExact:
DateTime result =
DateTime.ParseExact("20090212", "yyyyMMdd", CultureInfo.InvariantCulture);
Have a look at the DateTime.TryParseExact method (MSDN). I prefer TryParseExact method to the ParseExact method because it returns a boolean telling you whether or not the conversion was successful instead of throwing an exception but either one will work.
DateTime.ParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture);
... and I really doubt I got there first.
Although for completeness, I prefer TryParseExact
DateTime dt;
if(DateTime.TryParseExact(str, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt)) {
// ... use the variable dt
}

Problem in Datetime conversion in c#

I have a problem while converting a string whose value is dd.mm.yyyy to DateTime in c#
string OriginalDateFormat = "28.06.2009";
DateTime dt= Convert.ToDateTime(OriginalDateFormat);
Throwing an exception "String was not recognized as a valid DateTime."
But if it is in mm.dd.yyyy then it is running fine.
I googled and got lots of sites but all in vain
Any idea?
Thanks in advance.
Use DateTime.ParseExact and specify the exact format string:
DateTime dt = DateTime.ParseExact("28.06.2009", "dd'.'MM'.'yyyy",
CultureInfo.InvariantCulture);
If this is the value is from user input, you probably want to use DateTime.TryParseExact so you can handle failure gracefully:
DateTime dt;
if (DateTime.TryParseExact("28.06.2009", "dd'.'MM'.'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, // Default formatting options
out dt))
{
Console.WriteLine("Successfully parsed {0}", dt);
}
else
{
Console.WriteLine("Did not recognise date");
}
I think its an issue with culture...The format you specified is (I think) GB and the default culture is US.
You will need to specify the culture also.
Instead try this:
IFormatProvider culture = new CultureInfo("en-US", true);//en-Us or en-GB not sure
DateTime dt = DateTime.Parse(p, culture, DateTimeStyles.AssumeLocal);

Convert a string to a date in .net

I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
or
DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
More info in the MSDN documentation on ParseExact and TryParseExact.
you could try also TryParseExact for set exact format.
method, here's documentation: http://msdn.microsoft.com/en-us/library/ms131044.aspx
e.g.
DateTime outDt;
bool blnYYYMMDD =
DateTime.TryParseExact(yourString,"yyyyMMdd"
,CultureInfo.CurrentCulture,DateTimeStyles.None
, out outDt);
I hope i help you.
DateTime.TryParse method
You can also do Convert.ToDateTime
not sure the advantages of either
Using TryParse will not throw an exception if it fails. Also, TryParse will return True/False, indicating the success of the conversion.
Regards...
You can use the TryParse method to check validity and parse at same time.
DateTime output;
string input = "09/23/2008";
if (DateTime.TryParseExact(input,"MM/dd/yy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output) || DateTime.TryParseExact(input,"yyyyMMdd", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out output))
{
//handle valid date
}
else
{
//handle invalid date
}

Categories

Resources