I'm new to c# how can I convert my input string in to DateTime.
_toDate = 5/22/2015
I cannt use
DateTime.ParseExact(_toDate, "yyyy-MM-dd", null);
Or
Convert.ToDateTime(_toDate)
throw an exception String was not recognized as a valid DateTime.
Note : String shold be excact the same as above.
Appreciate your reply
Clearly, your string and format does not match.
From documentation;
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.
You need to use M/dd/yyyy with a culture that has / as a DateSeparator like InvariantCulture .
string _toDate = "5/22/2015";
DateTime myDate = DateTime.ParseExact(_toDate, "M/dd/yyyy", CultureInfo.InvariantCulture);
When you use null as an IFormatProvider, it's threaded as your CurrentCulture and if your CurrentCulture doesn't have / as a DateSeparator, you will get FormatException because / custom format specifier has a special meaning as replace me with current culture or supplied culture date separator.
Related
I have a string representing a date in a certain format, that I wish to format differently. Someone told me to use DateTime.(Try)ParseExact, so I did:
var dateString = "2016-02-26";
var formatString = "dd/MM/yyyy";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
You see, I want to format the date as dd/MM/yyyy, so 26/02/2016. However, this code throws a FormatException:
String was not recognized as a valid DateTime.
How can I format a DateTime differently?
First of all, DateTimes have no format. A DateTime holds a moment in time and a flag indicating whether that moment is Local, Utc or Unspecified.
The only moment a DateTime gets formatted, is when you output its value as a string.
The format string you provide to (Try)ParseExact is the format that the date(time) string to parse is in. See MSDN: Custom Date and Time Format Strings to learn how you can write your own format string.
So the code you're looking for to parse that string is this, and again, make sure the format string matches the format of the input date string exactly:
var dateString = "2016-02-26";
var formatString = "yyyy-MM-dd";
var parsedDate = DateTime.ParseExact(dateString, formatString, null);
Now parsedDate holds a DateTime value that you can output in your desired format (and note that you'll have to escape the /, as it'll be interpreted as "the date separator character for the current culture", as explained in above MSDN link):
var formattedDate = parsedDate.ToString("dd\\/MM\\/yyyy");
This will format the date in the desired format:
26/02/2016
You can use this for String date
DateTime.ParseExact(dateString, format, provider);
and for provider value
CultureInfo provider = CultureInfo.InvariantCulture;
as mentioned in Microsoft documentation
Hi I have a string in following format 23/03/2014 and I have tried to convert it to this format:
string npacked = Convert.ToDateTime(packeddate).ToString("yyyy/MM/dd");
But I am getting an error:
String was not recognized as a valid DateTime
Also tried this:
string npacked = DateTime.Parse(packeddate).ToString("yyyy/MM/dd");
but same error.
try with ParseExact with the format
string npacked = DateTime.ParseExact(packeddate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");
DEMO
Convert.ToDateTime is running a DateTime.Parse() on your string (23/03/2014). In the default culture (en-US) that is going to fail, since dates in that culture should be formatted MM/DD/YYYY. You need to switch to a different culture (like French) per MSDN:
// Reverse month and day to conform to the fr-FR culture.
// The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
dateString = "16/02/2008 12:15:12";
try {
dateValue = DateTime.Parse(dateString);
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
// Call another overload of Parse to successfully convert string
// formatted according to conventions of fr-FR culture.
try {
dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}'.", dateString);
}
Calling "ToString" afterwards has no effect whatsoever on the parse attempt, it just formats the output of the parse.
It may be due to your system date time format. You have mm-dd-yyyy format in your system and you are trying to parse it in dd-mm-yyyy format. Try changing your system date format to dd/MM/yyyy.
Convert.ToDateTime(string) calls DateTime.Parse(string, CultureInfo.CurrentCulture) explicitly. That means your both lines are equivalent.
In your profile, it says you are from Dubai, United Arab Emirates. That's why I assume your CurrentCulture is probably ar-AE at first but your string matches it's ShortDatePattern and that's why it prints;
Convert.ToDateTime("23/03/2014", new CultureInfo("ar-AE")) // 23/03/2014
But you didn't tell us what is your CurrentCulture, we never know.. But looks like your current culture's date seperator is not / or your current culture doesn't have standart date format dd/MM/yyyy (which is unlikely for most of cultures) your both lines fail (first scenario is more likely).
You can easly parse your string with a culture that has / as a DateSeparator using DateTime.ParseExact method. This method let's you specify your custom date formats. We can use InvariantCulture for example;
var date = DateTime.ParseExact("23/03/2014",
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
Now, let's consider to it's representation with yyyy/MM/dd format.
/ specifier has a special meaning of "replace me with the current culture's date separator" in custom date formats. That means if your date seperator is not / (I assume it is not) your date.ToString("yyyy/MM/dd") results will be included your date seperator, not /.
For example, I'm from Turkey, my culture is tr-TR. My date seperator is . (dot) That's why this example;
date.ToString("yyyy/MM/dd"); // Prints 2014.03.23 not 2014/03/23
In such a case, you can use a culture which has / a date seperator as a second parameter in your ToString method (InvariantCulture for example) like;
date.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture) // Prints 2014/03/23
or you can escape your / character regardless which culture you use like;
date.ToString(#"yyyy\/MM\/dd") // Prints 2014/03/23
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);
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.
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)