簡體   English   中英

將屬性值轉換為yyyy-MM-dd hh:mm:ss tt格式

[英]Convert the property value to yyyy-MM-dd hh:mm:ss tt format

我以以下方式保留日期時間信息的屬性

public string ExecutionTime{ get; set; }

ExecutionTime值設置為dd-MM-yyyy hh:mm:ss tt
如何更改屬性值以顯示為yyyy-MM-dd hh:mm:ss tt並在文本框中顯示。

我不會使用string屬性。 相反,我會將其存儲為DateTime因為它實際上似乎是一個。 您可以在顯示時隨意格式化

public DateTime ExecutionTime{ get; set; } 

例如:

Textbox1.Text = ExecutionTime.ToString("yyyy-MM-dd hh:mm:ss tt");

否則,您始終需要將該字符串解析為DateTime ,反之亦然,甚至可能會遇到本地化問題(將來)。

由於您的日期存儲為string

  1. 解析字符串以獲取實際的DateTime
  2. 轉換回不同格式的string

您將需要ParseExact

// Your date
string inputDate = "20-01-2012 02:25:50 AM";

// Converts to dateTime
// Do note that the InvariantCulture is used, as I've specified
// AM as the "tt" part of the date in the above example
DateTime theDate = DateTime.ParseExact(inputDate, "dd-MM-yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

// Now get the string to be displayed
// I've also specified the Invariant (US) culture, you might want something else
string yourString = theDate.ToString("yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture);

但是,您實際上應該將日期存儲為DateTime ,而不是string

DateTime d;
var isValid = DateTime.TryParse(ExecutionTime, out d);
if (isValid)
{
    textBox1.Text = d.ToString("dd-MM-yyyy hh:mm:ss tt");
}

暫無
暫無

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

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