DateTime picker C# format

耗尽温柔 提交于 2019-12-12 15:22:51

问题


I have a DateTime picker to add arrival time to a list, I have 2 questions about it:

  1. How can I get it to show dates like 12-Jan-2012 Instead of 12/01/12?
  2. How can I get it to show the time after the date but not the current time, as thats what is shows atm.

My current code is not very advanced its just:

theVisit.ArrivalTime = DateTimePicker1.Value

回答1:


Something like this will display the date and time:

DateTimePicker1.Value.ToString("d-MMM-yyyy hh:mm:ss");

To override the default DateTimePicker settings, you can do this:

DateTimePicker1.Format = DateTimePickerFormat.Custom;
DateTimePicker1.CustomFormat = "d-MMM-yyyy  hh:mm:ss";

You can show a different time by modifying the format string, e.g.:

DateTimePicker1.CustomFormat = "d-MMM-yyyy 12:00:00";

or even

DateTime otherTime = DateTime.Now;
DateTimePicker1.CustomFormat = "d-MMM-yyyy " + otherTime.ToString("hh:mm:ss");



回答2:


For it to show in that format in the picker, set the properties below

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd-MMM-yyyy  hh:mm:ss";



回答3:


You're looking for DateTime Format strings. There's a great article on them on MSDN. There's two types:

  1. Standard DateTime Formats
  2. Custom DateTime Formats

You can use these to construct the datetime to look how you want it to. For your example, you would use :

DateTimePicker1.Value.ToString("dd-MMM-yyyy hh:mm:ss")



回答4:


First, to alter how your DateTimePicker displays DateTimes:

DateTimePicker1.CustomFormat = "d-MMM-yyyy hh:mm:ss";
DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom;

Your code:

theVisit.ArrivalTime = DateTimePicker1.Value;

Would not change, because the DateTimePicker1.Value isn't any different, it's just displayed according to your format.

If you want the control to display a specific time (not the current time), you have to give the control that value:

DateTimePicker1.Value = new DateTime(2012, 12, 21, 23, 59, 59);

Otherwise it will display the current time as of the form creation.




回答5:


You may check datetimepicker like this to check if it is empty.

if(DatTimePicker1.Text.Equals(" "))
{
     MessageBox.Show("DateTimePicker is empty");
}


来源:https://stackoverflow.com/questions/13711358/datetime-picker-c-sharp-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!