user971741
user971741

Reputation:

Exchanging the formats for date in strings

I have a date in string with this format "2/11/2013 19:14:00" (MM/DD/YYYY HH:MM:SS) format and I want to convert it into a string of format like this 11 February 2013 19:14

How can I do it in most efficient way?

Upvotes: 0

Views: 58

Answers (3)

DrKoch
DrKoch

Reputation: 9772

First convert your string to a DateTime:

DateTime dt = DateTime.ParseExact(oldString, "M/dd/yyyy HH:mm:ss",
    CultureInfo.InvariantCulture);

then convert this DateTime to a string:

string newString = dt.ToString("dd MMMM yyyy HH:mm",
    CultureInfo.InvariantCulture);

Upvotes: 1

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

Reputation: 98750

If your 2/11/2013 19:14:00 value is a DateTime, just format your DateTime with .ToString() method like;

dateTimeValue.ToString("dd MMMM yyyy HH:mm", CultureInfo.InvariantCulture);

If your 2/11/2013 19:14:00 value is string, not a DateTime, you can parse it to DateTime first and then you can format it like;

string s = "2/11/2013 19:14:00";
DateTime dt;
if(DateTime.TryParseExact(s, "M/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture,
                          DateTimeStyles.None,
                          out dt))
{
  Console.WriteLine(dt.ToString("dd MMMM yyyy HH:mm",
                                 CultureInfo.InvariantCulture));
}

Here a demonstration.

Upvotes: 6

Patrick Hofman
Patrick Hofman

Reputation: 156978

If the input date is actually a string, the easiest thing to do is convert it to a DateTime first:

DateTime d = DateTime.ParseExact(oldDateString, "M/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Then convert it back to a string, as Soner already suggested:

string newDateString = d.ToString("dd MMMM yyyy HH:mm", CultureInfo.InvariantCulture);

Upvotes: 0

Related Questions