Gold
Gold

Reputation: 62524

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

Upvotes: 1

Views: 186

Answers (5)

Paweł Dyda
Paweł Dyda

Reputation: 18662

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.

Upvotes: 0

PrateekSaluja
PrateekSaluja

Reputation: 14936

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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502396

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?

Upvotes: 11

Xander
Xander

Reputation: 1133

DateTime dateFrom = DateTime.ParseExact("9/20/2010 3:32:32 PM", "M/dd/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

Works for me

Upvotes: 0

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27849

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")

Upvotes: 0

Related Questions