Rakesh
Rakesh

Reputation: 2790

Convert string to datetime and then back to string

Hi I am trying to convert a string to date time and then back to a string. This is my code.

try
{
    string dt = "19/9/13";
   DateTime.Parse(dt.ToString()).ToString("yyyy-MM-dd");

}
catch (Exception ex)
{
    string msg = ex.Message;
}

and also tried Convert.ToDateTime(dt.ToString()).ToString("yyyy-MM-dd");

I am getting this error String was not recognized as a valid DateTime.. can any one give a solution.

Upvotes: 0

Views: 1054

Answers (6)

Tim Schmelter
Tim Schmelter

Reputation: 460360

I don't know what culture you are using, however, by default it's date-separator is used. So if you for example use . as separator that won't work.

Use CultureInfo.InvariantCulture and DateTime.ParseExact:

DateTime dt DateTime.ParseExact("19/9/13", "dd/M/yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("yyyy-MM-dd");

Upvotes: 2

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8878

You should use DateTime.ParseExact:

DateTime.ParseExact(dt, "dd/M/yy").ToString("yyyy-MM-dd");

And take a look at Custom Date and Time Format Strings.

Upvotes: 1

Pascalz
Pascalz

Reputation: 2378

try with DateTime.ParseExact :

DateTime.ParseExact(dt.ToString(), "dd/M/yy", null).ToString("yyyy-MM-dd");

Upvotes: 1

S. S. Rawat
S. S. Rawat

Reputation: 6131

Use Convert.ToDateTime() to convert string into date.. and then date to string use ToString()

string dt = "19/9/13";
Convert.ToDateTime(dt);

Upvotes: 0

Misha Zaslavsky
Misha Zaslavsky

Reputation: 9712

Your parsing is true. The problem is the datetime because your computer supports another datetime format. It tries to get 19 as a month - and it throws this exception.

Probably if you write this it will work:

string dt = "9/19/13";

Or just change your computer settings to: dd/MMM/YYYY format.

Upvotes: 1

Carlos Landeras
Carlos Landeras

Reputation: 11063

Here you have:

string time = "19/9/13";

DateTime resds =DateTime.ParseExact(time, "dd/M/yy", System.Globalization.CultureInfo.InvariantCulture);

string datet = resds.ToShortDateString();

DateTime.ParseExact documentation

Upvotes: 2

Related Questions