Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

.net - format date in c#

How can I format a date as dd/mm/yyyy or mm/dd/yy ?

Like in VB format("dd/mm/yy",now)

How can I do this in C#?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's almost the same, simply use the DateTime.ToString() method, e.g:

DateTime.Now.ToString("dd/MM/yy");

Or:

DateTime dt = GetDate(); // GetDate() returns some date
dt.ToString("dd/MM/yy");

In addition, you might want to consider using one of the predefined date/time formats, e.g:

DateTime.Now.ToString("g");
// returns "02/01/2009 9:07 PM" for en-US
// or "01.02.2009 21:07" for de-CH 

These ensure that the format will be correct, independent of the current locale settings.

Check the following MSDN pages for more information


Some additional, related information:

If you want to display a date in a specific locale / culture, then there is an overload of the ToString() method that takes an IFormatProvider:

DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // returns "5/26/2009 10:39 PM"
dt.ToString("g", new CultureInfo("de-CH")); // returns "26.05.2009 22:39"

Or alternatively, you can set the CultureInfo of the current thread prior to formatting a date:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // returns "5/26/2009 10:39 PM"

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH");
dt.ToString("g"); // returns "26.05.2009 22:39"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...