Problem in Datetime conversion in c# - 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);

Related

System.FormatException: String was not recognized as a valid DateTime - when trying to convert MM/DD/YYYY

I have following C# method:
DateTime ConvertStringToDate(string dateInString)
{
try {
//string SSD = dateInString;
//DateTime date = Convert.ToDateTime(SSD);
//string strDate = String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", date);
//return Convert.ToDateTime(strDate);
return DateTime.ParseExact(dateInString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
catch (Exception) { }
return DateTime.Today;
}
The code in comment is another way I tried before.
I am in India and developing an ASP.NET WebForms application for my client in US. On one of its forms my client will enter the date in TextBox like 6/20/2018 which is MM/dd/yyyy format.
But in both the ways I am getting this error: System.FormatException: 'String was not recognized as a valid DateTime.'
I tried many solutions on SO but none of them are working.
return DateTime.ParseExact(dateInString, "M/d/yyyy", CultureInfo.InvariantCulture);
Check it here
The difference between my answer and Fabulous' one is that I also shortened dd to d so if your user writes 6/6/2018 it will work too
Your date format is MM/dd/yyyy and your input doesn't match. It is M/dd/yyyy
Based on your comment, to solve the 6/1/2018 issue, you'll need to do it as follows M/d/yyyy
Your format string is missing the AM/PM deisgnator:
return DateTime.ParseExact
(dateInString + " 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// Here ---------------------------------------------^
Try without concatenation with string " AM"
I was getting the same exception a couple of days ago when it was 9th of July, I simply appended a 0 with 9 to match the date format.
Try appending a 0 in your month to match the MM in your date format
Sometimes your system time and date format is not same as test format you can try to change system date and time format
If you want to convert this (01-01-2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM-dd-yyyy", CultureInfo.InvariantCulture);
If you want to convert this (01/01/2022) type of string into date
then try below code.
DateTime date = DateTime.ParseExact("01-01-2022", "MM/dd/yyyy", CultureInfo.InvariantCulture);

String to datetime in C#

I have a string strdate="25/9/2014" here in dd/MM/yyyy format.I want to parse it in date time like below
DateTime dt;
if (DateTime.TryParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
dt = DateTime.Parse(strDate);
}
Console.WriteLine(dt);
But it can not parse.Please help me.
Two things:
1: Your string format should be "dd/M/yyyy" (a double MM will require two month digits; a single M will allow 1 or 2 month digits).
2: You are parsing the date string twice.
Change your code to:
DateTime dt;
if (DateTime.TryParseExact(strDate, "dd/M/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("dd/M/yyyy"));
}
else
{
Console.WriteLine("Can't parse it.");
}
[EDIT] Changed the Console.WriteLine() so that it outputs in the specific "dd/M/yyyy" format rather than using the local system locale.
TryParseExact needs to match exactly.
In your case try dd/M/yyyy as your input is
25/9/2014
dd/M/yyyy
Change "dd/MM/yyyy" to "dd/M/yyyy"
because
TryParseExact looks for Exact Match

Why is the DateTime tryparse failing for the date 20140404

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().

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);

Better way to Select & Read Date in dd/mm/yy format?

In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format.
I use to change the culture info to UK format. So that the date will be selected from SQL server as in dd/mm/yy format.
But I know it's not good to play with CultureInfo. Even though I used like the following manner.
Any other better Ideas for me?
Sub Form_Load()
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)
End Sub
Any other better Ideas for me? Thanks for the Ideas.
Thanks & Regards.
From DateTime to string:
string s = DateTime.Today.ToString("dd/MM/yyyy");
From string to DateTime:
DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
In C# you could get the date string in desired format like,
string date = DateTime.Now.ToString("dd/MM/yyyy");
If you want to get DateTime object from string value representing DateTime in specific culture, you can do
DateTime dt = new DateTime();
DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
System.Globalization.DateTimeStyles.None, out dt);
DateTime --> String
DateTime.Now.ToString( new CultureInfo("fr-FR", false) );
String --> DateTime:
The preferred method would probably be DateTime.Parse()
dateString = "16/02/2008 12:15:12";
try
{
dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.
You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:
DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);
This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.
You can use DateTime.TryParse to parse the date...
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}
And even use an IFormatProvider to help TryParse work out the format.
CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
// Parsed correctly
}
else
{
// Invalid string!
}

Categories

Resources