Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 506
Gold Avatar asked Feb 01 '09 19:02

Gold


People also ask

What does Strftime mean in C?

strftime() is a function in C which is used to format date and time. It comes under the header file time. h, which also contains a structure named struct tm which is used to hold the time and date.

What is format mmm dd yyyy?

MMM/DD/YYYY. Three-letter abbreviation of the month, separator, two-digit day, separator, four-digit year (example: JUL/25/2003) YY/DDD. Last two digits of year, separator, three-digit Julian day (example: 99/349) DDD/YY.

How do you format mm dd yyyy?

dd/MM/yyyy — Example: 23/06/2013. yyyy/M/d — Example: 2013/6/23. yyyy-MM-dd — Example: 2013-06-23. yyyyMMddTHH:mmzzz — Example: 20130623T13:22-0500.

Is there a date type in C?

The C documentation about date indicates that you can use the time_t type which expresses a date with the number of seconds elapsed since a specific date called Epoch.


2 Answers

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

  • DateTime.ToString() method
  • Standard Date and Time Format Strings
  • Custom Date and Time Format Strings

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"
like image 72
M4N Avatar answered Oct 18 '22 23:10

M4N


string.Format("{0:dd/MM/yyyy}", DateTime.Now)

Look up "format strings" on MSDN to see all formatting options.

Use yy, yyyy, M, MM, MMM, MMMM, d, dd, ddd, dddd for the date component

Use h, hh, H, HH, m, mm, s, ss for the time-of-day component

like image 24
Arjan Einbu Avatar answered Oct 18 '22 22:10

Arjan Einbu