c# - Getting invalid month names in DateTime formatting -
i have simple program return day , shortdate. example, if input 27th march 2016, output "sun, 03/27/2016"
string shortmonthformat = "ddd"; datetime dtc = convert.todatetime("2016-03-27 12:26:41.210"); string result = dtc.tostring(string.format("{0}, {1}", shortmonthformat, dtc.toshortdatestring())); console.writeline(result); console.readline();
this code works current system date format mm/dd/yyyy
(03/27/2016). if system's date format changed dd-mmm-yy
(27-mar-16), code returning following output "sun, 27-3ar-16"
mar(march) returned "3ar"
aug(august) becomes "aua.d."
why happening?
because m
format specifier meaning single digit month number 1
12
, g
specifier means period or era such a.d.
since other characters doesn't referring any format specifiers, reflected output exactly are.
by way, code seems little bit complicated , buggy. first, generate format using shortmonthformat
, toshortdatestring
, generate string representation of datetime
that formatted string.
that's why code looks like;
string result = dtc.tostring("ddd, 27-mar-16");
which not too sense.
you can fix code use shortdatepattern
property of currentculture
instead of use dtc.toshortdatestring()
like;
string result = dtc.tostring(string.format("{0}, {1}", shortmonthformat, cultureinfo.currentculture.datetimeformat.shortdatepattern));
by way, based on variable name (which shortmonthformat
), ddd
specifier abbreviated day names. if wanna abbreviated month names, can use mmm
specifier instead.
string shortmonthformat = "mmm";
Comments
Post a Comment