2015-11-02 89 views
-1

當「DateTime.ParseExact」我有一個Nullable DateTime,我得到了一個錯誤:錯誤使用可空的DateTime

其他信息:字符串未被識別爲有效的DateTime。

我看着herehereherehere。我也試過String.Format("{0:s}", dateTime),但它不會改變我DateTime format.My代碼就像下面,

if (person.JsonData.PasswordChangeRequestTime != null) 
{ 
    DateTime data; 
    data = DateTime.ParseExact(((DateTime)person.JsonData.PasswordChangeRequestTime).Date.ToStringDateTime(), "dd'-'MM'-'yyyy HH':'mm':'ss", CultureInfo.InvariantCulture); 
    person.setColumnValue("passwordchangerequesttime", data); 
} 

我的一個DateTime的是這樣的: 1/1/2015 2:00:00 PM 我希望他們在 1-1-2015 14:00:00 是什麼格式我的DateTime.ParseExact函數錯了嗎?

順便說一句,我不希望使用subString功能!

+0

這是什麼方法 - 「ToStringDateTime()'? –

+0

@ shree.pat18我以爲它可能會將其轉換爲字符串!它不工作'(DATETIME)person.JsonData.PasswordChangeRequestTime).Date.ToString()' –

+0

你開始用'DateTime' - 但它是非常不清楚應該是什麼您的操作的最終結果(看起來像'DateTime'再次)。不會只是'data = person.JsonData.PasswordChangeRequestTime;'工作嗎? –

回答

2

你不需要做任何事情

你的(DateTime)person.JsonData.PasswordChangeRequestTime已經 a DateTime,你看到這可能是在調試器或什麼的。

A DateTime沒有任何隱式格式。它只有日期和時間值。格式概念只有當你得到它的文本(字符串)表示通常與DateTime.ToString()方法完成。

如果你想獲得它的確切字符串表示,可以用ToString方法與正確的格式和區域性設置喜歡的;

((DateTime)person.JsonData.PasswordChangeRequestTime) 
          .ToString("d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture) 

genereates 1/1/2015 2:00:00 PM

((DateTime)person.JsonData.PasswordChangeRequestTime) 
          .ToString("d-M-yyyy HH:mm:ss", CultureInfo.InvariantCulture) 

生成1-1-2015 14:00:00格式化的字符串。

如果您1/1/2015 2:00:00 PMstring,而不是一個DateTime,你需要將它與適當的格式解析到DateTime第一,然後生成它與適當的格式字符串表示爲好。

string s = "1/1/2015 2:00:00 PM"; 
DateTime dt; 
if(DateTime.TryParseExact(s, "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, 
          DateTimeStyles.None, out dt)) 
{ 
    dt.ToString("d-M-yyyy HH:mm:ss", CultureInfo.InvariantCulture); 
    // Generates 1-1-2015 14:00:00 
} 
+0

謝謝@SonerGönül!我的DateTime之一就是這樣的:'1/1/2015 2:00:00 PM'我希望他們的格式爲'1-1-2015 14:00:00'!它不適用於'((DateTime)person.JsonData.PasswordChangeRequestTime)'!!!順便說一下,我不想使用'subString'函數! –

+0

我也試過'data =((DateTime)person.JsonData.PasswordChangeRequestTime).ToString(「d-M-yyyy HH:mm:ss」,CultureInfo。InvariantCulture)「,但有一個錯誤:'不能隱式地將類型'字符串'轉換爲'system.DateTime'# –

+0

@DooshizePlusPlus編輯我的答案。看一看。你的代碼不會被編譯,因爲'ToString'方法返回'string',但你試圖將它分配給'DateTime'數據,並且它們之間沒有隱含的對話。 –