Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string represents date, and reformat it

Tags:

string

date

c#

The following case: There is a string that has this format "2012-02-25 07:53:04"

But in the end, i rather want to end up with this format "25-02-2012 07:53:04"

I think i have 2 options. 1 would be to reformat the string and move it all around, but i dont think this is a clean way of doing this.

A other way that i was thinking about is to save the source string to a date parameter, and then write the date parameter back to a string in a certain date format. But is this even possible to do ?

like image 428
Dante1986 Avatar asked Feb 19 '26 18:02

Dante1986


2 Answers

Do this:

DateTime.Parse("2012-02-25 07:53:04").ToString("dd-MM-yyyy hh:mm:ss");

Keep in mind this isn't culture-aware. And if you do need to store the intermediate result you could do that just as easily:

var myDate = DateTime.Parse("2012-02-25 07:53:04");
var myDateFormatted = myDate.ToString("dd-MM-yyyy hh:mm:ss");

Lastly, check out TryParse() if you can't guarantee the input format will always be valid.

like image 124
Yuck Avatar answered Feb 22 '26 06:02

Yuck


Others have suggested using Parse - but I'd recommend using TryParseExact or ParseExact, also specifying the invariant culture unless you really want to use the current culture. For example:

string input = "2012-02-25 07:53:04";

DateTime dateTime;
if (!DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss",
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.None,
                            out dateTime))
{
    Console.WriteLine("Couldn't parse value");
}
else
{
    string formatted = dateTime.ToString("dd-MM-yyyy HH:mm:ss",
                                         CultureInfo.InvariantCulture);
    Console.WriteLine("Formatted to: {0}", formatted);
}

Alternatively using Noda Time:

string input = "2012-02-25 07:53:04";

// These can be private static readonly fields. They're thread-safe
var inputPattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyy-MM-dd HH:mm:ss");
var outputPattern = LocalDateTimePattern.CreateWithInvariantInfo("dd-MM-yy HH:mm:ss");

var parsed = inputPattern.Parse(input);
if (!parsed.Success)
{
    Console.WriteLine("Couldn't parse value");
}
else
{
    string formatted = outputPattern.Format(parsed.Value);
    Console.WriteLine("Formatted to: {0}", formatted);
}
like image 44
Jon Skeet Avatar answered Feb 22 '26 07:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!