HOW TO:使用 Windows Forms DateTimePicker 控制項顯示自訂格式的日期How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control

Windows FormDateTimePicker控制項可讓您彈性地格式化日期和時間在控制項中的顯示。The Windows Forms DateTimePicker control gives you flexibility in formatting the display of dates and times in the control. Format屬性可讓您從預先定義的格式,在列出選取DateTimePickerFormatThe Format property allows you to select from predefined formats, listed in the DateTimePickerFormat. 其中一個項目是否適合您的目的,您可以建立您自己使用中所列的格式字元的格式樣式CustomFormatIf none of these is adequate for your purposes, you can create your own format style using format characters listed in CustomFormat.

若要顯示的自訂格式To display a custom format

  1. Format 屬性設定為 DateTimePickerFormat.CustomSet the Format property to DateTimePickerFormat.Custom.

  2. 設定CustomFormat屬性設為格式字串。Set the CustomFormat property to a format string.

    DateTimePicker1.Format = DateTimePickerFormat.Custom  
    ' Display the date as "Mon 27 Feb 2012".  
    DateTimePicker1.CustomFormat = "ddd dd MMM yyyy"  
    
    dateTimePicker1.Format = DateTimePickerFormat.Custom;  
    // Display the date as "Mon 27 Feb 2012".  
    dateTimePicker1.CustomFormat = "ddd dd MMM yyyy";  
    
    dateTimePicker1->Format = DateTimePickerFormat::Custom;  
    // Display the date as "Mon 27 Feb 2012".  
    dateTimePicker1->CustomFormat = "ddd dd MMM yyyy";  
    

將文字加入格式化的值To add text to the formatted value

  1. 使用單引號來括住的任何字元不是像"M"的格式字元或分隔符號,例如":"。Use single quotation marks to enclose any character that is not a format character like "M" or a delimiter like ":". 例如,下列的格式字串會顯示目前的日期格式 」 目前是:05:30:31 星期五年 3 月 02、 2012 「 英文 (美國) 文化特性中。For example, the format string below displays the current date with the format "Today is: 05:30:31 Friday March 02, 2012" in the English (United States) culture.

    DateTimePicker1.CustomFormat = "'Today is:' hh:mm:ss dddd MMMM dd, yyyy"  
    
    dateTimePicker1.CustomFormat = "'Today is:' hh:mm:ss dddd MMMM dd, yyyy";  
    
    dateTimePicker1->CustomFormat =  
       "'Today is:' hh:mm:ss dddd MMMM dd, yyyy";  
    

    根據文化特性設定,可能會變更任何沒有單引號括住的字元。Depending on the culture setting, any characters not enclosed in single quotation marks may be changed. 例如,上述的格式字串會顯示目前的日期格式 」 目前是:05:30:31 星期五年 3 月 02、 2012 「 英文 (美國) 文化特性中。For example, the format string above displays the current date with the format "Today is: 05:30:31 Friday March 02, 2012" in the English (United States) culture. 請注意第一個冒號會括在單引號括住,因為它不是會分隔字元,因為它是"ss"。Note that the first colon is enclosed in single quotation marks, because it is not intended to be a delimiting character as it is in "hh:mm:ss". 在另一個文化特性的格式可能會顯示為 「 目前是:05.30.31 星期五年 3 月 02、 2012"。In another culture, the format might appear as "Today is: 05.30.31 Friday March 02, 2012".

另請參閱See also