views:

99

answers:

5

Hi

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.

+1  A: 

DateTime time = DateTime.Now;
string format = "yyyy-M-d";
Console.WriteLine(time.ToString(format));

Woot4Moo
alternatively "yyyy-MM-dd" if your string can contain trailing zeros.
PVitt
+2  A: 

You can use

ToString( formatString )

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

Sachin Shanbhag
You are showing the overload that uses a `FormatProvider` and suggesting to use the one that uses a `string`. These are two _different_ overloads.
Oded
@Oded - Sorry, my mistake. I did not mean FormatProvider object there. I just meant it to be format string.
Sachin Shanbhag
+14  A: 

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.

Oded
What are the reasons it cant be parsed?
matskn
@matskn - if the string passed in is not a date `myString = "abcdsd"`.
Oded
If the provided format can not be applied on the string
bassfriend
A: 

The most efficient way is to use DateTime.TryParseExact():

DateTime result;
if (DateTime.TryParseExact(input, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out result))
{
    // use result
}
abatishchev
A: 

date.ToString("yyyy-MM-dd" );

Mazhar Karimi