Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a string to "year-month-day" format in C#

Im using a webservice that needs a datetime in the following format "2010-12-24"

I have the string to parse in the same "way" but as said, its a String.

string myDate = "2010-12-24";

How can i parse it so that it gets the same format?

Have tried using : DateTime.Parse(mystring);

but this gives me a colon separated format.

like image 239
matskn Avatar asked Oct 26 '10 12:10

matskn


2 Answers

Use DateTime.ParseExact, providing a custom format string:

DateTime.ParseExact(mystring, "yyyy-MM-dd", CultureInfo.InvariantCulture)

This will throw an exception if the input string cannot be parsed - you may want to use DateTime.TryParseExact which will return true if successful.

like image 76
Oded Avatar answered Oct 09 '22 21:10

Oded


You can use

ToString( formatString )

Eg:- dateTimeObj.ToString( "yyyy-MM-dd" ); Where dateTimeObj is your DateTime object

like image 40
Sachin Shanbhag Avatar answered Oct 09 '22 19:10

Sachin Shanbhag