views:

20

answers:

1

I have an object with a couple of DateTime properties:

public DateTime Start_Date { get; set; }
public DateTime? End_Date { get; set; }

I would like to set a format for each of these, along the lines of

Start_Date.ToString("M/d/yyyy hh:mm tt")

Do I have to code the get, or is there an elegant way to do this?

+1  A: 

You already have the code ... when you want to convert your date to a string in order to display it, call the tostring method and pass in the correct format string. If anything, for reusability, you could store the format in a local variable so that you don't have to type it more than one.

string format = "M/d/yyyy hh:mm tt";
string s = c.Start_Date.ToString(format);
string e = c.End_Date.HasValue ? c.End_Date.Value.ToString(format) : string.Empty;
Joel Martinez
I can create property StartDate { get { return StartDate.ToString(format); } } but I'm wondering if there's a better way?
chris
That entirely depends on what and how you want to do things. If you want your object to have a nicely formatted textual representation of the dates, then yes, simply write a string property with the getter as you mention :-)
Joel Martinez