-1

我有一个以下列方式保存日期时间信息的属性

public string ExecutionTime{ get; set; }

ExecutionTime 值设置为dd-MM-yyyy hh:mm:ss tt
如何将属性值更改为在文本框中yyyy-MM-dd hh:mm:ss tt显示和显示。

4

3 回答 3

4

我不会使用string财产。相反,我会将它存储为DateTime因为它实际上似乎是一个。当你显示它时,你可以随意格式化它。

public DateTime ExecutionTime{ get; set; } 

例如:

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

否则,您总是需要将该字符串解析为 a DateTime,反之亦然,您甚至可能会遇到本地化问题(将来)。

于 2012-12-14T12:58:05.807 回答
3

由于您的日期存储为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

于 2012-12-14T13:11:11.313 回答
1
DateTime d;
var isValid = DateTime.TryParse(ExecutionTime, out d);
if (isValid)
{
    textBox1.Text = d.ToString("dd-MM-yyyy hh:mm:ss tt");
}
于 2012-12-14T13:13:47.490 回答