Return today’s date in C# in specific format

Asked

Viewed 9,189 times

6

My way out has to be "2015-02-01"

I tried to get DateTime.Now.ToString("yyyy-m-d"), but she doesn’t 0 between days and months.

2 answers

9


If you want two digits, you need to specify two digits:

DateTime.Now.ToString("yyyy'-'MM'-'dd");
DateTime.Now.ToString("yyyy-MM-dd");

Watch out for the capital letters. m is minute, M is month.

See working on IDEONE.


It’s not in the question, but there are two important things that might be useful:

  • besides the Now, there is the UtcNow.

  • to convert UTC to local time, you have the ToLocalTime(). You can use linked to a specific Timezone if you prefer.


Follow the most common fields:

   d   dia do mês,  1-31
  dd   dia do mês, 01-31
 ddd   dia da semana ( Dom, Seg ... )
dddd   dia da semana ( Domingo ... )
   h   hora  1-12
  hh   hora 01-12
   H   hora  0-23
  HH   hora 00-23
   m   minuto  0-59
  mm   minuto 00-59
   M   mês     1-12
  MM   mês    01-12
 MMM   mês (Jan, Fev ... )
MMMM   mês (Janeiro ... )
   s   segundo  0-59
  ss   segundo 00-59
   t   A/P 
  tt   AM/PM
   y   ano     0-99
  yy   ano    00-00
 yyy   ano   000-999
yyyy   ano  0000-9999
   :   separador de tempo
   /   separador de data
"string" / 'string' valor literal

Official documentation:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110). aspx

5

There is already a response that meets the request, but there is a pattern that may be more appropriate depending on what is being done. Of course the specific need may be to use a format defined by the programmer right there, but in most cases the best is to use a known pattern rather than "invent" a pattern. So in most cases the most correct code for this is to use culture.

DateTime.Now.ToString(new CultureInfo("pt-BR", false).DateTimeFormat.ShortDatePattern)

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I gave an option using the current culture that should be the most suitable in most cases, after all it is common for the application to let the user’s general settings determine this and not what the programmer wants the user to see. Note that dotNetFiddle uses the American standard by default, so it is not expected. I also did it with invariant culture. The subject is extensive and does not fit here.

Obviously it is possible to use other cultures, including one that uses the standard year-month-day, for example: ko, pl, Sv, lt, Mn, km, si, ko-KR, pl-PL, Sv-SE, lt-LT, Mn-MN, km-KH, si-LK, se-SE, fr-CA, en-CA, smj-SE, en-ZA, Sma-SE, Sma, Mn-Cyrl, smj.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.