C# 将属性值转换为 yyyy-MM-dd hh:mm:ss tt 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13879120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:02:02  来源:igfitidea点击:

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

c#asp.net.netc#-4.0c#-3.0

提问by Vikas Kunte

i have a property in the following way to keep datetime information

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

public string ExecutionTime{ get; set; }

public string ExecutionTime{ get; set; }

ExecutionTime value is set as dd-MM-yyyy hh:mm:ss tt
How can i change the property value to appear as yyyy-MM-dd hh:mm:ss ttand show in a textbox.

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

采纳答案by ken2k

As your date is stored as string:

由于您的日期存储为string

  1. Parse the string to get the actual DateTime
  2. Convert back to stringwith different format
  1. 解析字符串以获取实际 DateTime
  2. 转换回string不同的格式

You'll need ParseExact:

你需要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);

But you really should store a date as DateTime, not string.

但是您确实应该将日期存储为DateTime,而不是string

回答by Tim Schmelter

I wouldn't use a stringproperty. Instead i would store it as DateTimesince it actually seems to be one. You can format it howsoever you want when you display it.

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

public DateTime ExecutionTime{ get; set; } 

for example:

例如:

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

Otherwise you always need to parse that string to a DateTimeand vice-versa and you might even run into localization issues (in future).

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

回答by spajce

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