2014-11-04 192 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

相關問題