You can use ToShortDateString
as Habib suggests.
It depends on CultureInfo.CurrentCulture
because while CultureInfo
holds a variety of information about matters that generally vary due to language and locality, but include personal preferences. Hence while for me while CurrentCulture.Name
returns en-IE
, DateTime.Now.ToShortDateString()
returns 2014-01-24
rather than 24/01/2014
as one would get by using the object returned from CultureInfo.GetCultureInfo("en-IE")
, because my own rig is set up to use en-IE for language and ISO 8601 for dates and times.
Therefore, don't worry about the name of the current culture and current UI culture relating solely to its language; they can have UseUserOverride
set to true and actually be constructed from the user's settings.
As well as Habib's suggestion, if you want to use the current short date string (or that from any other CultureInfo
you can use the string "d"
. This gives no advantage in your case where the short date string is all that is used, but it's useful if it will be part of a larger phrase:
string.Format("Today is {0:d}.", DateTime.Now)
(On my system, Today is 2014-01-24.
on yours perhaps something else).
There are other useful single-string formatting strings for dates, that can be similarly used.
Edit:
Since you've just pointed out that you are using a DateTime?
rather than a DateTime
, then you've three options:
- Use
DateOfBirth = string.Format("{0:d}", myTable.DateOfBirth)
. This results in an empty string for null cases.
- Test for nullity with
string.Format
, e.g. DateOfBirth = myTable.DateOfBirth.HasValue ? string.Format("Born on {0:d}.", myTable.DateOfBirth.Value) : "Date of birth unknown";
- Test for nullity with
ToShortDateString
; DateOfBirth = myTable.DateOfBirth.HasValue ? myTable.DateOfBirth.ToShortDateString() : "Date of birth unknown";
.