this code return to me 'M/d/yyyy'
but I need 'mm/dd/yyyy'
how do this?
((CultureInfo)Session["culture"]).DateTimeFormat.ShortDatePattern)
this code return to me 'M/d/yyyy'
but I need 'mm/dd/yyyy'
how do this?
((CultureInfo)Session["culture"]).DateTimeFormat.ShortDatePattern)
That dosn't make much since... The pattern you want is for a specific culture.. For instance:
DateTime.Now.ToString(CultureInfo.GetCultureInfo("en-US").DateTimeFormat.ShortDatePattern);
Will return mm/dd/yyyy
but
DateTime.Now.ToString(CultureInfo.GetCultureInfo("en-GB").DateTimeFormat.ShortDatePattern);
will return dd/mm/yyyy
.
From the code you added, it's not very clear - it seems you're getting a specific culture but then want to override the ShortDatePattern
...
If this is true, why use the Culture received in the session in the first place? Use whatever pattern you want without regarding the culture.
e.g. DateTime.Now.ToString("MM/dd/yyyy");
(Anyways, it IS possible to override, as ShortDatePattern
can be set, just like @mipe34 showed in the comments)
You can override how dates are displayed by specifying the template you want in the ToString
method:
DateTime.Now.ToString("MM/dd/yyyy")) //Will display "12/21/2012"
You appear to be using a CultureInfo
object, which contains default formats (and other cultural information such as currency) and is provided by the operating system.
Calling DateTime.Now.ToShortDateString()
by itself will use the format specified by ShortDatePattern
in the current thread's culture, which can be set with something like:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
You mean you want to change the property? This is simple:
((CultureInfo)Session["culture"]).DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
However, if the CultureInfo
happens to be read-only, it will throw run-time. In that case maybe you can assign a new CultureInfo
object? If you can, do it like this:
// get reference
var ci = (CultureInfo)Session["culture"];
// clone and reassign to get rid of read-only:
ci = (CultureInfo)(ci.Clone());
// change property:
ci.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
// make read-only again
ci = CultureInfo.ReadOnly(ci);
// assign back to your "source":
Session["culture"] = ci;
After that, when people call someDateTimeValue.ToShortDateString()
on some new thread whose CurrentCulture
is taken from Session["culture"]
, they will get your new format.
Note: "m"
or "mm"
is minutes, and "M"
or "MM"
is months. Also "/"
is the DateSeparator
of the culture (which might translate to a dash (-
) or something else in some cultures).