簡體   English   中英

轉換日期時間

[英]Convert DateTime

這有效:

testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", null);

這不是:

string somedate = "16/10/2010";
testDateTime = DateTime.ParseExact(somedate, "dd/MM/yyyy", null);

為什么??

這兩個代碼段是絕對等效的,應該/不能相同地工作。 我懷疑somedate變量的值不是您認為的應用程序內部的值。 嘗試調試。

您的兩個示例都是等效的,並且如果您當前的文化是美國,也可以使用,但不一定適用於所有其他文化。

例如,以下內容將引發FormatException,因為de-DE文化使用句點作為分隔符(16.10.2010):

System.Threading.Thread.CurrentThread.CurrentCulture =
             CultureInfo.CreateSpecificCulture("de-DE");
DateTime testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", null);

通常,最好的做法是(FxCop會警告它)在可用時始終指定IFormatProvider參數:如果要分析當前用戶的輸入,通常為CultureInfo.CurrentCulture;否則為50。 或CultureInfo.InvariantCulture(如果您正在解析來自外部源的輸入)。

// For input from the current user (16.10.2010 in Germany)
testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", CultureInfo.CurrentCulture);

// For input from an external source in a defined culture-invariant format
testDateTime = DateTime.ParseExact("16/10/2010", "dd/MM/yyyy", CultureInfo.InvariantCulture);

當我嘗試它時,它工作正常……只是復制並粘貼了它。

插入一個斷點,將指針放在變量上,然后檢查月,日和年成員。 如果它們不是權利,請告訴我們您看到的內容。

如果您使用打印或msgbox顯示變量的值,則可能是您不希望輸出使用掩碼/格式。

當我嘗試時,這兩件事對我都起作用。 您遇到什么錯誤?

ParseExact()使用第二個參數解析您的輸入字符串,而不返回該格式的值。

編輯:從下面的喬的評論-您將獲得的輸出將為“ MM / dd / yyyy”格式”-輸出將為沒有任何固有格式的DateTime類型。

您正在嘗試更改DateTime格式嗎? 您不能使用DateTime對象執行此操作。 僅當使用String.Format:String.Format(“ {0:d / M / yyyy HH:mm:ss}”,dt)顯示DateTime對象時,才可以更改格式。 (例如其他方法)

由於某種原因,它對我不起作用,直到我添加了此代碼:CultureInfo.InvariantCulture

DateTime.ParseExact(sValue,“ dd / MM / yyyy”,CultureInfo.InvariantCulture);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM