Getting error while parsing string to datetime - c#

I have a datetime value in a CSV file and below is the sample data:
20/06/2016 11:52
21/06/2016 11:52
22/06/2016 11:52
Non when I try to parse this datetime, I get error:
String was not recognized as a valid DateTime.
I am not sure what will be the format of this date but I would always like to parse it in that culture in which my application will be using. So based on current culture I would like to parse my date.
This is how I am trying but getting error as above:
string row = "20/06/2016 11:52"
Try 1:
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime dateValue;
DateTime.TryParse(rowValue, culture, styles, out dateValue); // {1/1/0001 12:00:00 AM}
Try 2
DateTimeFormatInfo usDtfi = new CultureInfo(culture.Name, false).DateTimeFormat;
var l = Convert.ToDateTime(rowValue, usDtfi); //String was not recognized as a valid DateTime
var g = DateTime.Parse(rowValue, usDtfi);//String was not recognized as a valid DateTime
All this above approches are failing and I would like to have exact date and want to store in my SQL Server database table.
My system datetime is in format : mm/dd/yy
I have already seen some questions like below:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Datetime format Issue: String was not recognized as a valid DateTime
But all those answers are specifying date format but I don't know what will be the format; that is why I am trying to detect from current culture. I am not sure whether I am thinking in a right way.

If you're sure that each string you encounter will be in a proper format, but you just don't know which one, one thing you can do is get an array of all the different formats on your machine and use that in the parse exact method:
var formats = (from CultureInfo ct in CultureInfo.GetCultures(CultureTypes.AllCultures)
select ct.DateTimeFormat.GetAllDateTimePatterns()).SelectMany((x) => x).ToArray();
DateTime test = DateTime.ParseExact("20/06/2016 11:52", formats, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
That code on my machine generates over 26,000 formats. As long the string follows one of them it will be accepted.
If getting the proper format will be inconsistent you could go this route:
var formats = (from CultureInfo ct in CultureInfo.GetCultures(CultureTypes.AllCultures)
select ct.DateTimeFormat);
string dateString = "20/06/2016 11:52";
DateTime temp = new DateTime(0);
foreach (DateTimeFormatInfo dfi in formats)
{
if (DateTime.TryParseExact(dateString, dfi.GetAllDateTimePatterns(), dfi, DateTimeStyles.None, out temp))
{
break;
}
}
if(temp == new DateTime(0))
{
//save string to get it's format
}

If you are 100% sure the format will always be the same, you can use the method ParseExact like:
var parsedDate = DateTime.ParseExact(row, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);

Related

Change DateTime Format {"MM/dd/yyyy"} to {"dd/MM/yyyy"} and time should remain same in Unity

I want to change DateTime now to the Format {"MM/dd/yyyy"} using this code.
string.Format("{0:MM:dd:yyyy}", DateTime.Now)
and saving it.
after getting saved string I get DateTime in format {"MM/dd/yyyy"} . Now I want to convert it in another format so I can Parse to DateTime. when I try to parse MM/dd/yyyy to DateTime got an error
"FormatException: String was not recognized as a valid DateTime."
Thanks in Advance.
You can rather use DateTime.ParseExact which allows you to specify the exact date format you are expeting the input to have.
For example
var now = DateTime.Now;
Debug.Log(now.ToString("dd.MM.yyyy"));
var example1 = now.ToString("MM/dd/yyyy");
Debug.Log(example1);
var readTime1 = DateTime.ParseExact(example1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime1.ToString("dd.MM.yyyy"));
var example2 = now.ToString("dd/MM/yyyy");
Debug.Log(example2);
var readTime2 = DateTime.ParseExact(example2, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Debug.Log(readTime2.ToString("dd.MM.yyyy"));
See Fiddle
The format is only relevant for display
If you save it in a C# DateTime variable, there is no "format" when saving it, this DateTime is a struct data type which is universal and not bound to any specific format
If you want to use a specific format for parsing, you can use:
// Parse date and time with custom specifier.
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
DateTime myDate = DateTime.ParseExact(dateString, format, provider);
You can use CultureInfo to optimize your format for you needs
If there is a need to save it as "MM/dd/yyyy", your should save it as string
best regards

date to be converted to UK date format with preserving 0's

I want my date to be converted to UK date format.
so example if its 26/2/2016 then it should be converted to 26/02/2016.
if its a 2/13/2016 then it should be converted to 13/02/2016.
The end result should be UK format with preserving 0 in day and month.
Code
string cellvalue;
string oData = "2/13/2016";
if (DateTime.TryParse((string)oData, CultureInfo.CurrentUICulture, styles, out dt))
{
cellvalue = dt.ToString("dd/MM/yyyy");
Console.WriteLine(cellvalue + "go to hell");
}
else
{
cellvalue = oData.ToString();
Console.WriteLine(cellvalue + "go to bokaro");
}
Easyyy:
CultureInfo enGB = new CultureInfo("en-GB");
string oData = "2/13/2016";
DateTime dateValue;
// Parse date with no style flags.
dateString = "13/02/2016";
DateTime.TryParseExact(oData, "g", enGB, DateTimeStyles.None, out dateValue);
As far as I understand you want resulting date to be in default UK format i.e. dd/MM/yyyy no matter if input date string is in MM/dd/yyyy or dd/MM/yyyy, former being default format for US dates.
You were close in the code you have already tried. Additionally you need to one thing - if input is in US format, parse it as DateTime using US culture, and then simply transform to UK.
var UKCulture = new CultureInfo("en-GB");
var USCulture = new CultureInfo("en-US");
DateTime dt;
string cellvalue;
string oData = "13/2/2016";
// First try parsing to UK format
if (!DateTime.TryParse(oData, UKCulture, DateTimeStyles.None, out dt))
{
// If fails, then try US format
DateTime.TryParse(oData, USCulture, DateTimeStyles.None, out dt);
}
// Once you have DateTime instance, you can do anything. Parsing is over.
cellvalue = dt.ToString("dd/MM/yyyy");
Console.Write(cellvalue);
So now this gives final value as 13/02/2016 for both 2/13/2016 and 13/2/2016 inputs.

Convert english Date with parse exact

I try to convert a english date to an german, but my format is not good.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime currentCultureDate = DateTime.Now;
string format = "dd.MM.yyyy HH:mm:ss";
Console.WriteLine("Format: " + format);
Console.WriteLine("Original Date: " + currentCultureDate);
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
Console.WriteLine("Converted Date: " + convertedDate);
FormatException.....
DateTime.ParseExact is used to create a DateTime from a string. You can pass a DateTimeFormat or CultureInfo which will be used to convert that string to DateTime.
The method does not convert it to a string in another CultureInfo, say de-DE. Therefore you can use DateTime.ToString:
string germanFormat = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss", new CultureInfo("de-DE"));
You are not doing what you say: Your code actually tries to parse the date in German format:
// This is German format
string format = "dd.MM.yyyy HH:mm:ss";
// This takes a date and parses it using the ABOVE FORMAT - which is German
DateTime convertedDate = DateTime.ParseExact(currentCultureDate.ToString(), format, new CultureInfo("de-DE"));
If you already have a DateTime you want to output in German format, you don't need ParseExact, but ToString:
string german = DateTime.Now.ToString(format, new CultureInfo("de-DE"));
A DateTime itself doesn't have any culture formatting attached. It is just a date and a time. Only when you output a DateTime, it somehow needs to be converted into a string and to do so, culture information is required. So the rule of thumb is:
If you get a string that represents a date and time value, you need to parse it into a DateTime, either using a fixed format and ParseExact or relying on the framework, passing the source culture information to Parse or TryParse.
If you have a DateTime and want to output it, you need to format it using ToString, providing either a fixed format string and culture information, or use ToString only for the current thread's culture.

Error : String was not recognised as a valid date time

when i am trying to connect c# code to mysql database there is a mistake in date datatype
try
{
CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP");
DateTime d = DateTime.ParseExact(accountend, "yyyy/MM/dd", CultureInfoDateCulture);
return true;
}
catch
{
return false;
}
when i have to collect date from the month calender i have used this validation for MYSQL and the datatype i have used is DATE datatpe
I have been getting the folllowing error
String was not recognised as a valid date time
please help me guys.... Thanks in advance
MYSQL Date Format is yyyy-MM-dd so you should use the same format while parsing it in the DateTime.ParseExact() method.
Try This:
DateTime d = DateTime.ParseExact(accountend, "yyyy-MM-dd",
CultureInfoDateCulture);
EDIT : From Your Comments your Date Format is M/d/yyyy
Try This:
DateTime d = DateTime.ParseExact(accountend, "M/d/yyyy",
CultureInfoDateCulture);
DateTime.ParseExact requires that the format string represent accurately the day, month and year of the string that need to be converted
So assuming that your date string is 4/11/2014 (day, month, year) you need
try
{
CultureInfo CultureInfoDateCulture = new CultureInfo("ja-JP");
DateTime d = DateTime.ParseExact(accountend, "d/M/yyyy", CultureInfoDateCulture);
return true;
}
catch
{
return false;
}
instead if the format is month, day, year, the format string is
DateTime d = DateTime.ParseExact(accountend, "M/d/yyyy", CultureInfoDateCulture);
By the way, your date is in the format expected by the InvariantCulture, so you could avoid the creation of the CultureInfo in this context, it is enough to use
DateTime d = DateTime.Parse(accountend, CultureInfo.InvariantCulture);

How to Convert a Date String with Format "dd/MM/yyyy" to OS Current Culture Date Format

A string has the value in "dd/MM/yyyy" format like "04/10/2012". This should be converted to a Date w.r.t Current Culture of OS.
I have tried below string with Korean as Current Culture of OS in which date format is yyyy-MM-dd, my code is not getting correct Month value, it interchange the month value with day:
Input: "04/10/2012"
Output: 2012-04-10
Code:
DateTime DT;
string dt = "04/10/2012";
DateTimeFormatInfo DateInfo = CultureInfo.CurrentCulture.DateTimeFormat;
DT = Convert.ToDateTime(String.Format ("{0:"+DateInfo .ShortDatePattern +"}", dt.Trim ()), CultureInfo .CurrentCulture);
MessageBox.Show("Date: " + DT.ToShortDateString());
How I can fix that ?
It looks to me like you need to parse it with a fixed format, I think you are currently parsing it with a format other than "dd/MM/yyyy" and because the date is ambiguous (as in, month and day can be interchanged without causing invalid dates) the format is simply switching the month and day value. When you then go to output it, it looks reversed.
Use DateTime.ParseExact to force the parsing format and then use the built-in current culture sensitive string output methods on DateTime to get a formatted string:
var date = DateTime.ParseExact("04/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture);
MessageBox.Show("Date: " + date.ToShortDateString()); // Assumes current culture is controlling format
Since your input string is in a fixed format, you should parse it in that format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
If you string has the format dd/MM/yyyy then you have to use DateTime.ParseExact with the specified format:
DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Anything else will try an interpret the string according to the current culture's rules - which, as you have found, will fail.
why not use ToShortDateTimeString()

Categories

Resources