sansactions
sansactions

Reputation: 243

string to DateTime(date)

I am trying to parse a string i recieved from my webservice into a DateTime so i can look if the date of that datetime is today or not.

I looked a bit and found on msdn and stackoverflow that these possibilities should work, they do not work for me for some reason.

string starttime = obj.TIME; //time i get from webservice = "02/14/2017 00:00:00"
DateTime startTimeCon = DateTime.Parse(starttime);
DateTime startTimeCon2 = Convert.ToDateTime(starttime);

error:

The string is not recognised as a valid DateTime

Any ideas why?

Upvotes: 0

Views: 114

Answers (1)

Roman
Roman

Reputation: 12201

It seems you have different culture in your system.

Use ParseExact() instead of Parse():

DateTime startTimeCon = DateTime.ParseExact(starttime, 
                                            "MM/dd/yyyy HH:mm:ss",
                                            CultureInfo.InvariantCulture);

HH used for 24 hours, you can use hh for 12 hours

Also, you can set appropriate culture in Parse():

DateTime startTimeCon = DateTime.Parse(starttime, neededCulture);

Upvotes: 7

Related Questions