开发者

MM/dd/yyyy format

I have the following:

PMRCutoffDate.Value = ReportCalc.Cutoff_Date.ToString("MM/dd/yyyy");
PM开发者_Go百科RDate.Value = DateTime.Now.ToString("MM/dd/yyyy");

i want dates to show up as: 03/05/2010, not 3/5/2010 or 03/5/2010 or 3/05/2010

However, my program STILL shows the date incorrectly (3/10/2010).

Any ideas on what's wrong?


In VS 2008 I have the following code with the output you are looking for. Can you post more information? Code:

Console.WriteLine(DateTime.Now.ToString("MM/dd/yyyy"));

Output:

03/10/2010


According to this article you can 0 pad the dates with String.format or DateTime.toString like so:

String.Format("{0:MM/dd/yyyy}", dt);


Check in Control Panel's Regional and Language Options applet if the date format was changed. You ought to be able to insulate yourself from these overrides or unusual culture properties by using the CultureInfo.InvariantCulture.DateTimeFormat property in the DateTime.ToString() overload.


Textbox1.Text = DateTime.Today.ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);

OUTPUT: 09/18/2015


The above replies should help you out already but if not and you are still having problems you could create the following extension method for DateTime and just force it to the format you need regardless of culture setup:

public static class StringExtension
{
    static public string ToStringFormatted(this DateTime dt)
    {
        return string.Format("{0:00}/{1:00}/{2:0000}", dt.Month, dt.Day, dt.Year);
    }

    // if the culture info change does fix your issue do:
    static public string ToStringFormatted2(this DateTime dt)
    {
        return dt.ToString("MM/dd/yyyy");
    }
}

// useage:
string date = DateTime.Now.ToStringFormatted();

// output:  03/10/2010

I prefer extension methods for formatting things like dates as well because someone always has the bright idea of wanting to change the format at some point and I only have to change the extension and my entire app now reflects the new format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜