user559142
user559142

Reputation: 12517

Set Datetime format - C#

I have the following property within a user control:

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

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

Upvotes: 5

Views: 17199

Answers (6)

Sinista
Sinista

Reputation: 457

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

Upvotes: 0

dknaack
dknaack

Reputation: 60486

Description

A DateTime has no format but you can change the Display Format using the CustomFormat property.

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

Sample

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

More Information

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

The DateTime property itself doesn't carry a specific format - it's a neutral representation of the datetime. It's the input control's format that you should be setting. The DateTimeInput control probably has a "FormatString" property, but that depends on the control. Are you using WPF? ASP.NET? WinForms?

Upvotes: 1

n8wrl
n8wrl

Reputation: 19765

The datatype you're returning - DateTime - itself doesn't 'have' a format. I'd suggest leaving it to your caller for decide on the formatting, or implement an additional property that returns a string and formats according to your wishes.

Upvotes: 0

Huske
Huske

Reputation: 9296

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

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

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

Upvotes: 3

Yuck
Yuck

Reputation: 50855

DateTime? (i.e. Nullable<DateTime>) does not have implicit formatting. You'll need to format the value in whatever UI you're working with or change your property (or add a new one) to return a 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
    }
}

Upvotes: 1

Related Questions