I want to parse DateTime, here my code:
var datastring =p1.ItemArray[2].ToString();
var format = "dd.MM.yyyy";
var date = DateTime.ParseExact(datastring,format,CultureInfo.InvariantCulture);
p1 - is DataRow
, in p1.ItemArray[2]
I have value of DateTime
In watch p1.ItemArray[2]
have this value : "09/03/2012 00:00:00"
his type is DateTime
After parsing throws error: String was not recognized as a valid DateTime.
You could include the time in your format as it seems the string you are trying to parse contains the time:
var format = "dd/MM/yyyy hh:mm:ss";
Also I would recommend you using the TryParseExact method as it provides a better defensive programming pattern instead of throwing exceptions.
IMHO you should use
var datastring = p1.ItemArray[2].ToString();
var format = "dd/MM/yyyy HH:mm:ss";
var date = DateTime.ParseExact(datastring, format, CultureInfo.InvariantCulture);
With ParseExact
you must provide exact format of date contained in string
Change this:
var format = "dd.MM.yyyy";
With this:
var format = "dd/MM/yyyy HH:mm:ss";
because parseExact will expect to receive the same format that you specified which is "dd.MM.yyyy". You can try:
var format = "dd.MM.yyyy";
var datastring =p1.ItemArray[2].ToString(format);
Most probably due to the difference between your Server locale and the UI locale
One easier method will be to specify the globalization details in the web.config
like
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
OR in more detail
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" />
But be sure this wont clash with your application in general
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.