简体   繁体   中英

how to give a custom format to dateTimePicker in c#

I want to show Date and Time in format like (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). 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

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.

The Format and CustomFormat of the DateTimePicker only relate to what's displayed in the DateTimePicker. The Value property is a DateTime and has no specific connection to the control. 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. If you call ToShortDateString then you're going to use the default short date format for the system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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