简体   繁体   English

如何在C#中为dateTimePicker提供自定义格式

[英]how to give a custom format to dateTimePicker in c#

I want to show Date and Time in format like (2-13-2014). 我想以(2-13-2014)这样的格式显示日期和时间。 How would I do it. 我该怎么办。 Here is My code. 这是我的代码。 I try this but it shows me Date and Time like this (2/13/2014). 我尝试了此操作,但它向我显示了这样的日期和时间(2/13/2014)。 Please help me 请帮我

private void buttonSave_Click(object sender, EventArgs e)
{
     dateTimePicker1.Format = DateTimePickerFormat.Custom;
     dateTimePicker1.CustomFormat = "dd-MM-yyyy";

     MessageBox.Show(dateTimePicker1.Value.ToShortDateString());
}

I assume you want to show February 1, 2014 as 2-1-2014 , so this code should work 我假设您想将February 1, 2014显示为2-1-2014 ,因此此代码应该有效

MessageBox.Show(dateTimePicker1.Value.ToString("M-d-yyyy"));

You can also change "Md-yyyy" to any format you like, see @Dumisani's comment below for the reference. 您也可以将"Md-yyyy"更改为所需的任何格式,请参阅下面的@Dumisani评论。

The Format and CustomFormat of the DateTimePicker only relate to what's displayed in the DateTimePicker. DateTimePicker的Format和CustomFormat仅与DateTimePicker中显示的内容有关。 The Value property is a DateTime and has no specific connection to the control. Value属性是DateTime,并且没有与控件的特定连接。 It's a binary value that has no format. 这是没有格式的二进制值。 If you want to display a DateTime in a particular format then you have to specify that format when you convert it to a string, regardless of where it came from in the first place. 如果要以特定格式显示DateTime,则必须首先将其转换为字符串时指定该格式,而不管其最初来自何处。 If you call ToShortDateString then you're going to use the default short date format for the system. 如果调用ToShortDateString,那么您将为系统使用默认的短日期格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM