Codehelp
Codehelp

Reputation: 4777

Converting string to date time

I have a date which comes in a string like so:

09/25/2014 09:18:24

I need it like this (yyyy-mm-dd):

2014-09-25 09:18:24

The object that this date goes into is a nullable date.

Tried this does not work:

DateTime formattedDate;
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd",
               CultureInfo.InvariantCulture,
               DateTimeStyles.None,
               out formattedDate);

Any clues?

Thanks in advance.

Upvotes: 1

Views: 128

Answers (3)

Stefano Bafaro
Stefano Bafaro

Reputation: 913

In answer to your question, to convert it as you prefer, do it like this:

string originalDate = "09/25/2014 09:18:24";

DateTime formattedDate;

if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate))
{
    string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
}

And then output will have your desired format.

Upvotes: 1

Satinder singh
Satinder singh

Reputation: 10208

DateTime  dateOf = Convert.ToDateTime("09/25/2014 09:18:24");
string myFormat = "yyyy-mm-dd";
string myDate = dateOf.ToString(myFormat);  // output 2014-18-25 

Datetime format

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98848

From DateTime.TryParseExact

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly.

In your case, they are not. Use yyyy-MM-dd HH:mm:ss format instead.

string s = "2014-09-25 09:18:24";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss",
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
}

It is a little bit unclear but if your string is 09/25/2014 09:18:24, then you can use MM/dd/yyyy HH:mm:ss format instead. Just a tip, "/" custom format specifier has a special meaning as replace me with current culture or supplied culture date separator. That means, if your CurrentCulture or supplied culture's DateSeparator is not /, your parsing operation will fail even if your format and string matches exactly.

If you have already a DateTime and you want to format it, you can use DateTime.ToString(string) method like;

dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25

or

dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24

Remember, a DateTime does not have any implicit format. It just contains date and time values. String representations of them have formats.

Upvotes: 4

Related Questions