Convert to dateTime from string (arabic culture to english) - c#

string strHijdt ="29-02-1435";
DateTime hdt = DateTime.ParseExact(strHijdt, "dd/MMM/yyyy HH:MI24",
CultureInfo.InvariantCulture);
Getting error while convert to string("29-02-1435") to datetime

2/1435 has 28 days only
so, below will work
string aa="28-02-1435";
DateTime hdt = DateTime.ParseExact(aa, "dd-MM-yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(hdt.ToLongDateString());
DEMO
since you have given input as 29-02-1435 even you provide correct date time format (dd-MM-yyyy) you will get error for the invalid date

Two problems here:
1. As mentioned above, expected format for does not match string (there is no time, different separator)
2. If your date string is in Hijri calendar, you should either provide correct culture explicitly or use system culture (pass null for IFormatProvider):
string strHijdt = "29-02-1435";
var culture = CultureInfo.GetCultureInfo("ar-SA");
DateTime hdt = DateTime.ParseExact(strHijdt, "dd-MM-yyyy", culture);

Related

C#-"String was not recognized as a valid DateTime" exception

I have this code in my controller.this code gives an exception when i'm trying to loop through a DataSet.The exception is given on different rows when i run the project several times.(The exception is not happen at exact row)
The exception is;
String was not recognized as a valid DateTime.
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
i tried this too;
DateTime createdDate = DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
but it is not working yet..
the value of the row is 2/9/2016 21:20
You just have to cast it to the right type which seems to be DateTime, no need to parse:
DateTime arrDate = ds.Tables[0].Rows[i].Field<DateTime>("CheckInDate");
If it's actually a string(why is that so?) use M/d/yyyy instead of MM/dd/yyyy:
DateTime.ParseExact("2/9/2016 21:20", "M/d/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
ParseExact requires that your string exactly matches the pattern you are parsing against.
Your pattern has "MM/dd" which requires double digit months and days ("01/29" or "10/02" or "01/02") but you are only passing in single digit months and days ("2/9").
You either need to change the pattern to accept single digits or change the string to pass double digits.
you need to know in which format the date is retrieved then parse it with the proper format
DateTime dt=DateTime.ParseExact(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
if this format is not apropiate for the current culture (the language and region of the application)
// for example language English and region Canada
DateTime dt=DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString(), new CultureInfo("en-CA"));
OR
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString()); //uses the current Thread's culture
For more informations, check out Custom Date and Time Format Strings
Try below,
If ( ds.Tables[0].Rows[i]["CheckInDate"] != null ) {
// your code goes here...
DateTime arrDate = DateTime.Parse(ds.Tables[0].Rows[i]["CheckInDate"].ToString());
}

DateTime.ParseExact() - DateTime pattern 'y' appears more than once with different values

I have spent a day trying to get DateTime.ParseExact() to work based on this correctly answered question at Parse string to DateTime in C# however, I cannot get the answer to work.
Here is my code:
string testDateRaw = #"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd H:mm:ss.yyy";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate);
Error:
DateTime pattern 'y' appears more than once with different values.
Note: error reported in original version of the post does not show up in this sample, but may be related:
"When converting a string to DateTime, parse the string before putting each variable into the DateTime object."
Your format should be yyyy-MM-dd HH:mm:ss.fff
string testDateRaw = #"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd HH:mm:ss.fff";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate);
See: Custom Date and Time Format Strings
The error I get with that code is the following:
DateTime pattern 'y' appears more than once with different values.
It's pretty self-explanatory. Looking at the docs, you need to use .fff here:
"yyyy-MM-dd H:mm:ss.fff"
yyy is: The year, with a minimum of three digits, but since you already have yyyy in your pattern, you get the duplicate specifier error.
Your format is wrong, you used y twice.
string testDateRaw = #"2014-05-21 10:08:15.965";
string format = "yyyy-MM-dd H:mm:ss.fff";
DateTime testDate = DateTime.ParseExact(testDateRaw, format, CultureInfo.InvariantCulture);
System.Console.WriteLine(testDate);

String was not recognized as a valid DateTime when string is 13/07/15

I have a string date = 13/07/15 in this format and I want to convert it into DateTime, but I get the error mentioned below
String was not recognized as a valid DateTime.
What can I do to convert into datetime. I have tried this
DateTime dt = Convert.ToDateTime(date);
Never noticed that different cultures write their data and time in different formats? Although the format you use is valid in most Western European countries it is rubbish in the United States.
To overcome this problem, you can ask the system for the current date and time format:
var currentCulture = System.Globalization.CultureInfor.CurrentCulture
IFormatProvider dateTimeFormat = currentCulture.DateTimeFormat;
string dateTxt = #"13/7/2015";
System.DateTime myDate = System.DateTime.Parse(dateTxt, dateTimeFormat);
That should do the trick if your computer has the correct culture.
If you want to be able to understand a lot of cultures, don't ask for the current culture but use one of the constructors of System.Globalization.CultureInfo
Not wise, because does 1/3/2015 mean March 1st, or January 3rd?
Your code DateTime dt = Convert.ToDateTime(date); is perfect. Seems to me like the error is in your database, because it converts it into date if it gets the full year. Please check it in your database.
Do like this,
DateTime date = DateTime.ParseExact(s, "dd/MM/yy", null);
Source : DateTime.ParseExact

Console application string was not recognised as valid datetime

I have a excel sheet in which am taking a date column in this format "23/8/11 01:33:01:PM"
and am inserting it in sql 2008 using datarow but am getting a error
String was not recognised as valid datetime.
Can any one please help?
DateTime newdate = Convert.ToDateTime(row[8].ToString());
Here how Convert.ToDateTime method looks like when you decompile it;
public static DateTime ToDateTime(string value)
{
if (value == null)
return new DateTime(0L);
else
return DateTime.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}
As you can see, this method use DateTime.Parse method with your CurrentCulture. And if your string doesn't match your current culture date format, your code will be broken. That's the reason you get this error.
Use DateTime.ParseExact with "dd/M/yy hh:mm:ss:tt" format instead.
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.
string s = "23/8/11 01:33:01:PM";
DateTime newdate = DateTime.ParseExact(s, "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
Console.WriteLine(newdate);
Output will be;
8/23/2011 1:33:01 PM
Here a DEMO.
For your case;
DateTime newdate = DateTime.ParseExact(row[8].ToString(), "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
For more informations, take a look;
Custom Date and Time Format Strings
Convert.ToDateTime internally calls DateTime.Parse which by default will use the current culture of your application. If 23/8/11 01:33:01:PM is not a valid format for this culture then this method will fail.
For specific date formats it's best to use DateTime.ParseExact e.g.
DateTime.ParseExact("23/8/11 01:33:01:PM", "dd/M/yy hh:mm:ss:tt", CultureInfo.InvariantCulture);
This approach makes your code culture independent which means the date will always be parsed correctly (given it's in the specified format).
This will work:
DateTime newdate = Convert.ToDateTime("8/23/11 01:33:01 PM");
I changed day and month and removed the colon a the end. But that is very specific. You need to know more about the dates passed to do that.

Get DateTime Obj from "mm/yyyy" format Date string

I have a date string in format "08/1999" I want to get the first date of the corresponding month. eg : in this case 08/01/1999.
It is simple for en-Us culture. I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring) but this is valid for en-US culture only.
How can I do this for different culture ?
My datestring will always be in mm/yyyy format. and I am trying to obtain a DataTime obj from this dateString.
Use ParseExact method. Note upper-cased M's are for months and lower-cased m's for minutes.
string dateToConvert = "08/1999";
string format = "MM/yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact(dateToConvert, format, provider);
Output:
{1999-08-01 00:00:00}
You can also use Convert.ToDateTime and Parse methods. It will produce the same result, but in implicite way:
DateTime result = Convert.ToDateTime(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
DateTime result = DateTime.Parse(dateToConvert, provider); // Output: {1999-08-01 00:00:00}
Read more at:
Parsing Date and Time Strings
Standard Date and Time Format Strings
Custom Date and Time Format Strings
I'm not sure if I understand your question correctly, but you can try passing CultureInfo.InvariantCulture if you want to force the US date format regardless of the regional settings of the client computer:
DateTime.Parse("08/1999", System.Globalization.CultureInfo.InvariantCulture)
I break the string, append "01" in the string to get 08/01/1999 and then DateTime.Parse(datestring)
That's a very long-winded way to do it. Simply this will work:
DateTime.Parse("08/1999")
How can I do this for different culture ?
If your string is always in this format, do this:
DateTime.Parse("08/1999", CultureInfo.InvariantCulture)

Categories