How can I convert this datetime format from a webservice. The datetime value is: \"timestamp\": \"2014-04-18T14:45:00+02:00\" I wan\'t to convert it to: dd.mm.YYYY hh.mm.ss
Use DateTime.ParseExact(string, string, IFormatProvider)
or DateTime.TryParseExact(string, string, IFormatProvider, DateTimeStyles, out DateTime
).
With a regex you can do the following:
string resultString = null;
try {
resultString = Regex.Replace(subjectString, @"(\d{4})-(\d{2})-(\d{2})\w{1}(\d{2}):(\d{2}):(\d{2})\+\d{2}:\d{2}", "$3.$2.$1 $4.$5.$6", RegexOptions.IgnoreCase);
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
//18.04.2014 14.45.00
You need to use "yyyy-MM-dd'T'HH:mm:ssK"
format with InvariantCulture using DateTime.ParseExact method like;
string s = "2014-04-18T14:45:00+02:00";
var date = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
CultureInfo.InvariantCulture);
Take a look at The "K" Custom Format Specifier
Then you can get string representation of your DateTime
with DateTime.ToString() method. DateTime
has no inherent format, it has just a value. You can get string representation for formatting.
date.ToString("dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture);
//18.04.2014 03.45.00
Here a demonstration.
Remember, mm
is for minutes, MM
for months. And hh
is for 12-hour clock which is 01
to 12
. But HH
is 24-hour clock which is 00
to 23
.
That's why you can't parse 14
with hh
specifier. I assume your real representation format is dd.MM.yyyy HH.mm.ss
EDIT: After your comment, you can use "MM/dd/yyyy HH:mm:ss"
format like;
string s = "04/18/2014 14:45:00";
var date = DateTime.ParseExact(s, "MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Console.WriteLine(date); // 18/04/2014 14:45:00
string date = "2014-04-18T14:45:00+02:00";
var results = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);