Problem with date type
i receive this date: 9/20/2010 3:32:32 PM
i need to convert to datetime.
i try:
DateTime DateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM", "dd/M/yyyy", CultureInfo.InvariantCulture);
but i get error: String was not recognized 开发者_开发百科as a valid DateTime.
in my computer the region is: Hebrew (Israel) dd/MM/yyyy for short date and hh:mm for short time
how to fix it ?
thank's in advance
If you're receiving "9/20/2010 3:32:32 PM" as a string, then trying to parse it as if it were in the "dd/MM/yyyy" format is clearly wrong - that's try to use a month of 20. You're also only parsing part of the string - you need to either trim your string or provide the complete format.
Try this:
DateTime dateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM",
"M/dd/yyyy h:mm:ss tt",
CultureInfo.InvariantCulture);
Note that using this sort of strict parsing will only work if you can guarantee that that will always be the format. Where are you getting this data from?
How could it work man.You are converting into "dd/MM/yyyy " & putting month as 20.In your question dd/M/yyyy is wrong.It will like dd/MM/yyyy.
By default format is MM/DD/yyyy.
simple way to do .......
DateTime DateFrom = DateTime.Parse("9/20/2010 3:32:32 PM");
if you want to provide a specific Format so use like that
DateTime DateFrom = DateTime.ParseExact("20/09/2010 3:32:32 PM", "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
I hope it works.
It looks like your original date string is in a US format (i.e. m/dd/yyyy). Try replacing your third parameter with new CultureInfo("en-US")
DateTime dateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM", "M/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Works for me
I wouldn't use ParseExact() when I know that time string is formatted by invariant culture.
DateTime dateFrom = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
is both more compact and more clear.
精彩评论