将日期时间显示为 MM/dd/yyyy HH:mm 格式 c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16017979/
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
Display datetime into MM/dd/yyyy HH:mm format c#
提问by Priya
In database datetime is being stored in MM-dd-yyyy HH:mm:ss fromat.
However, I want to display datetime in "MM/dd/yyyy HH:mm" format.
I tried it by using String.Format().
在数据库中,日期时间存储在 MM-dd-yyyy HH:mm:ss fromat 中。
但是,我想以“MM/dd/yyyy HH:mm”格式显示日期时间。我通过使用 String.Format() 进行了尝试。
txtCampaignStartDate.Text = String.Format("{0:MM/dd/yyyy
HH:mm}",appCampaignModel.CampaignStartDateTime);
Here appCampaignModel.CampaignStartDateTimeis DateTime object having value in "MM-dd-yyyy HH:mm" format.
这appCampaignModel.CampaignStartDateTime是 DateTime 对象,其值为“MM-dd-yyyy HH:mm”格式。
I want to display in "MM/dd/yyyy HH:mm" format.
我想以“MM/dd/yyyy HH:mm”格式显示。
Can anyone help me for this?
任何人都可以帮助我吗?
采纳答案by Tim Schmelter
The slashes in this format MM/dd/yyyy HH:mmmean: "replace me with the actual separator of the current culture". You have to use CultureInfo.InvariantCultureexplicitely:
这种格式中的斜杠MM/dd/yyyy HH:mm表示:“用当前文化的实际分隔符替换我”。您必须CultureInfo.InvariantCulture明确使用:
txtCampaignStartDate.Text = appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
The "/" Custom Format Specifier
In database datetime is being stored in MM-dd-yyyy HH:mm:ss fromat.
在数据库中,日期时间存储在 MM-dd-yyyy HH:mm:ss fromat 中。
Don't store datetimeswith a format which means that you store them as (n)varchar. Use datetimeinstead.
不要datetimes以一种格式存储,这意味着您将它们存储为(n)varchar. 使用datetime来代替。
回答by Matt Busche
Why not just a simple replace?
为什么不只是一个简单的替换?
txtCampaignStartDate.Text = BadString.Replace("-","/");
回答by Pranay Rana
txtCampaignStartDate.Text = appCampaignModel.CampaignStartDateTime
.ToString().Replace("-","/");
or
或者
String.Format("{0:MM/dd/yyyy HH:mm}", dt);
Check : String Format for DateTime [C#]
or
或者
String date = dt.ToString("MM/dd/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
回答by Luuk Krijnen
try using an added culture info:
尝试使用添加的文化信息:
CultureInfo ci = new CultureInfo("en-US");
txtCampaignStartDate.Text =
appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm", ci);
p.s. the culture info used is an example.
ps 使用的文化信息是一个例子。
回答by Yeronimo
Since you already have a DateTime object, just ToString it how you want:
由于您已经有一个 DateTime 对象,只需 ToString 即可:
appCampaignModel.CampaignStartDateTime.ToString("MM/dd/yyyy HH:mm");

