编程语言
首页 > 编程语言> > c#-.net获得DateTimeFormat“ G”

c#-.net获得DateTimeFormat“ G”

作者:互联网

我想使用DataGridView显示日期,并使用DateTimePicker实现过滤器.我希望它们都以“ G”格式显示日期时间Standard Date and Time Format.理想情况下,我会这样做

dateTimePicker1.CustomFormat = "G";

但这似乎不起作用. (它在DateTimePicker中实际上显示了字符“ G”.)我发现了以下解决方法,但对我来说却显得脆弱和麻烦.

DateTime now = DateTime.Now;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns('G')[0];
dateTimePicker1.Value = now;

dataGridView.Rows.Add(now);

有什么改进建议吗?

编辑:添加了我设置dateTimePicker1.Format.

解决方法:

您可以使用:

var formatInfo = CultureInfo.CurrentCulture.DateTimeFormat;
string pattern = formatInfo.ShortDatePattern + " " + formatInfo.LongTimePattern;

遵循MSDN docs for ‘G’状态:

The “G” standard format specifier represents a combination of the short date (“d”) and long time (“T”) patterns, separated by a space.

标签:c,net,datetimepicker
来源: https://codeday.me/bug/20191030/1971374.html