2014-11-04 187 views
1

我有进来像这样一个字符串的日期:转换字符串到日期时间

09/25/2014 09:18:24 

我需要像这样(YYYY-MM-DD):

2014年9月25日09 :18:24

该日期进入的对象是可以空的日期。

试过这不起作用:

DateTime formattedDate; 
bool result = DateTime.TryParseExact(modifiedDate, "yyyy-MM-dd", 
       CultureInfo.InvariantCulture, 
       DateTimeStyles.None, 
       out formattedDate); 

任何线索?

在此先感谢。

+0

[转换字符串为DateTime C#的.NET]的可能重复(http://stackoverflow.com/questions/919244/converting-string-to-datetime-c-net) – 2014-11-04 11:15:35

+0

你对打扰和解析感到困惑吗?如果输入字符串是“09/25/2014”,为什么要用'yyyy-MM-dd'解析它? – 2014-11-04 11:17:04

+0

对于'DateTime'存储的内容,您似乎也感到困惑......它不包含*格式......它只是一个日期和时间。看到http://stackoverflow.com/questions/9763278 – 2014-11-04 11:19:15

回答

1

在回答你的问题,将其转换为您喜欢,像这样做:

string originalDate = "09/25/2014 09:18:24"; 

DateTime formattedDate; 

if (DateTime.TryParseExact(originalDate, "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out formattedDate)) 
{ 
    string output = formattedDate.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); 
} 

然后输出将有你想要的格式。

+0

不起作用。 formattedDate仍然有斜杠。 – Codehelp 2014-11-04 11:25:25

+0

@Codehelp我编辑我的答案,试试这个:) – 2014-11-04 11:38:29

4

DateTime.TryParseExact

一个日期和时间其 日期时间等效的指定字符串表示形式转换。 字符串表示的格式必须为 与指定的格式完全匹配。

就你而言,它们不是。改为使用yyyy-MM-dd HH:mm:ss格式。

string s = "2014-09-25 09:18:24"; 
DateTime dt; 
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", 
          CultureInfo.InvariantCulture, 
          DateTimeStyles.None, out dt)) 
{ 
    Console.WriteLine(dt); 
} 

这是一个有点不清楚,但如果你的字符串是09/25/2014 09:18:24,那么你可以使用MM/dd/yyyy HH:mm:ss格式代替。只是一个小费,"/" custom format specifier具有特殊含义作为取代我与当前文化或提供文化日期分隔。这意味着,如果您的CurrentCulture或提供的文化的DateSeparator不是/,则如果您的格式和字符串完全匹配,则您的解析操作将失败甚至

如果你有已经一个DateTime并要格式化它,你可以使用DateTime.ToString(string) method等;

dt.ToString("yyyy-mm-dd", CultureInfo.InvariantCulture); // 2014-09-25 

dt.ToString("yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture); // 2014-09-25 09:18:24 

记住,DateTime没有任何隐含格式。它只包含日期和时间值。它们的字符串表示有格式。

+0

不起作用。 TryParseExact失败。可能与斜杠不在输入字符串中有关。没有? – Codehelp 2014-11-04 11:24:54

+0

@Codehelp哪一个不行?你的'modifiedDate'究竟是什么?你有一个'DateTime',你想要格式化它,或者你有一个特定格式的字符串,你想解析它?是的/ character有一个特殊的含义,正如我在回答中所说的那样,但是因为你使用了InvariantCulture,所以这不是问题。 – 2014-11-04 11:28:18

+0

好吧,试过Stefano的答案,将其转换为DateTime,然后尝试使用ToString。它仍然是相同的。 – Codehelp 2014-11-04 11:31:10

0
DateTime dateOf = Convert.ToDateTime("09/25/2014 09:18:24"); 
string myFormat = "yyyy-mm-dd"; 
string myDate = dateOf.ToString(myFormat); // output 2014-18-25 

Datetime format

+0

为什么你使用'ddd','MMM'和'd'格式呢?它们与问题无关。 – 2014-11-04 11:35:53

+0

@SonerGönül:更新的日期格式 – 2014-11-04 11:42:50

+1

尽管使用'Convert.ToDateTime(string)'方法,但不保证您的'CurrentCulture'解析'MM/dd/yyyy HH:mm:ss'格式的字符串, IFormatProvider'。 – 2014-11-04 11:44:22

相关问题