Error : String was not recognized as a valid DateTime while converting to date format in c#
Solution 1
This works:
DateTime.ParseExact(dtStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture)
ParseExact
and TryParseExact
allows to use a custom format string. ddd
is the abbreviated day name, MMM
the abbreviated month name, dd
the day number, HH
hours in 24h clock format, mm
minutes, ss
seconds, zzzz
the time-zone and yyyy
the years.
I have used CultureInfo.InvariantCulture
to specify that the current culture is not used but InvariantCulture
which is similar to "en-US"
.
works but after getting date from your line of code i tried to do date.ToString("dd/mm/yyyy") but get the string as 12-12-2013, no slashes
/
is a replacement character for your current culture's date-separator which is obviously -
. So also use CultureInfo.InvariantCulture
to specify that the separator should be used without using your current culture:
string result = dateTime.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
Solution 2
Try this
DateTime.ParseExact(YourDate, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture)
Its better to use Invariant culture than Current culture
Solution 3
You are trying to convert a non-standard format, so use this:
string dateStr = "Thu Jul 18 17:39:53 +0000 2013";
DateTime date = DateTime.ParseExact(dateStr, "ddd MMM dd h:mm:ss KKKK yyyy", System.Globalization.CultureInfo.InvariantCulture);
Or build the correct format for your input.
Comments
-
iJade over 3 years
Here is the date time format i'm trying to format.I'm getting this date format from twitter apis
string date = "Thu Jul 18 17:39:53 +0000 2013"
i tried
Convert.ToDateTime(date).ToString("dd/MM/yyyy")
But it says
String was not recognized as a valid DateTime.