开发者

How do I keep the 0's in a Date

I am trying to figure out how it is that I can keep the 0's or add them when I grab a date.

What Im getting is this:

6/15/2010

What I'm tring to get is:

06/15/2010

I have added it so that it checks the length to and if its less than 6 (im stripping the "/") it pads the left side. That solves the issue when the month is a single digit, but what about when the date is a single digit.

My ultimate goal is to have a date such as:

1/1/2010

read out lik开发者_运维问答e:

01/01/2010

Any suggestions would be greatly appreciated.


Use a custom format : dd/MM/yyyy, or in your case MM/dd/yyyy. Note the capital M, the small m gets you the minutes.

string s = DateTime.Now.ToString("MM/dd/yyyy");


You need to use a custom DateTime format string:

string str = someDate.ToString("dd/MM/yyyy");


It depends on the format of date you are using.

For instance, dd/MM/yyyy will produce 01/05/2009 and d/M/yyyy would produce 1/5/2009

A complete reference can be found there : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx


You want something like this:

string myDate = "1/1/2010";
DateTime date = DateTime.Parse(myDate);
string formattedDate = date.ToString("MM/dd/yyyy");

If the starting date is some other unrecognized format you could use DateTime.ParseExact();


Use DateTime.ParseExact() to parse the string into a valid datetime object and then use DateTime.ToString("dd/MM/yyyy") to get result in desired format.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜