Set Datetime Format - C #

I have the following property in a user control:

public DateTime? Value { get { return DatePickerInput.SelectedDate; } set { DatePickerInput.SelectedDate = value; } } 

This allows you to select dates in the following format 01-Feb-2012 . I want to change the format so that it returns dates in dd/MM/yy format ... how is this possible?

+4
source share
6 answers

It uses the current culture settings on your computer. If you need this format, you need to return it as a string or let your receiving method convert it to a string. For instance:

 string myFormat = Value.ToString("dd/MM/yyyy"); 

I did not take into account that your Value property can also return null. This is just to show you how to format the result.

+3
source

DateTime? (ie Nullable<DateTime> ) does not have an implicit format. You will need to format the value in any user interface you are working with, or change your property (or add a new one) to return the String value instead:

 public String FormattedValue { get { return DatePickerInput.SelectedDate.HasValue ? DatePickerInput.SelectedDate.Value.ToString("dd/MM/yy") : ""; // return an empty string if SelectedDate is null } } 
+1
source

The DateTime property itself does not have a specific format - it is a neutral representation of date and time. This is the input format you must set. The DateTimeInput control probably has a FormatString property, but it depends on the control. Do you use WPF? ASP.NET? Winforms?

+1
source

Description

A DateTime does not have a format , but you can change the display format using the CustomFormat property.

By default, the display format depends on Thread.CurrentThread.CurrentCulture .

Example

 myDateTimePicker.Format = DateTimePickerFormat.Custom; myDateTimePicker.CustomFormat = "dd/MM/yy"; 

Additional Information

+1
source

The data type that you return - DateTime - does not, in itself, have a "format". I suggest leaving it to your subscriber to decide on formatting or implement an additional property that returns a string and formats in accordance with your wishes.

0
source

Take a look at this Microsoft document: Standard Data and Time Format .

0
source

Source: https://habr.com/ru/post/1396195/


All Articles