簡體   English   中英

如何在C#中將日期(來自日期時間輸入字段)轉換為另一種日期格式?

[英]How to Convert Date(from date time input field) to another date format in C#?

我在從日期獲取日期並將其轉換為另一種格式的日期時間輸入字段中

try
{
    DateTime dt = dtiFrom.Value.Date;
    string format = "DD-MM-YYYY"; // Use this format
    MessageBox.Show(dt.ToString(format)); // here its shows result as DD-10-YYYY
    DateTime dt1 = Convert.ToDateTime(dt.ToString(format)); // here Error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0."
}
catch (Exception ee)
{
    MessageBox.Show(ee.Message, "Error Message!");
}

我無法根據我的格式轉換日期。 請任何人幫助我編寫代碼或向我推薦一些代碼。 提前致謝

您的格式應如下:

string format = "dd-MM-yyyy";

大小寫對於字符串格式很重要,您可能會覺得月份使用大寫字母很奇怪,但這是因為小寫的mmm用於表示分鍾。

請注意,您的輸出顯示DDYYYY的原因是,任何未保留為格式字符的字符將被輸出而不會發生任何變化。 大寫字母DY未被保留,這就是為什么它們在輸出中顯示的原因,就像-保持不變。

如果您希望輸出保留格式的字符,則可以使用\\對其進行轉義。

請參閱此處以獲取日期和時間格式值的完整列表

日期模式格式應更改,最好使用TryParseExact而不是使用Convert

DateTime dt = dtiFrom.Value.Date;
string format = "dd-MM-yyyy";
DateTime dt1 = new DateTime();

if (DateTime.TryParseExact(dt , format, null , DateTimeStyles.None, out dt1))
{
  // you can use dt1 here
}
else
{
  MessageBox.Show("Error Massage");
}

暫無
暫無

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

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