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\"
Parse as DateTime then reformat it. Be careful: use always an IFormatProvider!
Yes, you can use custom DateTime format strings to parse and reformat DateTime objects.
DateTime date = DateTime.ParseExact("2012-02-25 07:53:04", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string formattedDated = date.ToString("dd-MM-yyyy HH:mm:ss");
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);
}
You can parse this as a date object and then provide the formatting you want when using the date.ToString method:
date.ToString("dd-MM-yyyy hh:mm:ss");
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.
Yes, it is quite possible. All you need to do is use DateTime.Parse
to parse the string
into a DateTime
struct and then use ToString()
to write the date back out to another string with the format you want.