0

the string is 20131024174621 which is year =2013, month=10, date=24, hours=17, minutes=46, seconds=21 What I am trying to do is to convert and format it into 2013-10-24 17:46:21. I have tried my luck as the code below however it return such error :

String was not recognized as a valid DateTime.

String timestamp = "20131024174621";
String converted = DateTime.Parse(timestamp).ToString("yyyy-MM-dd HH:mm:ss");

What should be the way of doing it right?

4

3 回答 3

4

You have to use ParseExact.

void Main()
{
    String timestamp = "20131024174621";
    var date = DateTime.ParseExact(timestamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
    Console.WriteLine (date.ToString("yyyy-MM-dd HH:mm:ss"));
}

Output:

2013-10-24 17:46:21

于 2013-10-24T10:05:33.997 回答
3
DateTime.ParseExact( timestamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture ).ToString( "yyyy-MM-dd HH:mm:ss" );
于 2013-10-24T10:03:31.583 回答
1

Since other two answer is correct, I want to point the root of your problem.

DateTime.Parse method uses Standard Date and Time Format Strings. From How Standard Format Strings Work

In a formatting operation, a standard format string is simply an alias for a custom format string. The advantage of using an alias to refer to a custom format string is that, although the alias remains invariant, the custom format string itself can vary. This is important because the string representations of date and time values typically vary by culture. For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd"

In 20131024174621 string, you need yyyyMMddHHmmss format for your current culture. Looks like your culture doesn't have this format and that's why you get this error.

For this kind of non-standart format string, you can use custom date format.

Any string that is not a standard date and time format string is interpreted as a custom date and time format string.

As I wrote in third paragraph, this kind of date formats is based on culture. When you have this kind of custom date strings, in most case using DateTime.ParseExact Method (String, String, IFormatProvider) with specific culture is the best choice.

于 2013-10-24T10:39:22.067 回答