格式化日期时间

时间:2010-07-02 14:57:40

标签: c# datetime

嘿那里,我正在提取创建文件的日期和时间。日期应该是2010年7月1日下午2:08,但格式是从我的应用程序调用时的2:08:07 01/07/2010。我希望它在文件浏览器中显示(2010年7月1日下午2:08)。我怎么能做到这一点?

    string createdOnCMM = Creationtime; //this returns the 2:08:07 01/07/2010 


// I think I need a modified verison of the following to reformat it

    DateTime dt = Convert.ToDateTime(createdOnCMM);
    String.Format("0:{dd/MM/yyyy HH:mm:ss}", dt);

3 个答案:

答案 0 :(得分:4)

您的复合格式字符串不太正确。试试这个:

string s = string.Format("{0:dd/MM/yyyy HH:mm:ss}", dt);

或者,如果想要格式化DateTime,请直接调用ToString:

string s = dt.ToString("dd/MM/yyyy HH:mm:ss");

(这是一种更具可读性的方法,IMO。)

请注意,目前这是特定于文化的。 可能可以用于您的预期用途,但您应该知道它。

答案 1 :(得分:3)

Microsoft's Standard Date and Time Format Strings开始,您应该可以使用g格式字符串获得您想要的内容,如下所示:

String.Format("{0:g}", dateTimeValue);

这应该会产生你想要的格式。

答案 2 :(得分:2)

如果您只需要使用当前文化的短日期字符串进行格式化,请使用Eric's answer中提到的g说明符。

如果您需要您提到的确切格式,无论您目前的文化如何,那么以下其中一项应该可以解决问题:

string formatted = dt.ToString("M'/'d'/'yyyy h':'mm tt");

// or

string formatted = string.Format("{0:M'/'d'/'yyyy h':'mm tt}", dt);