Return today's date in C # in specific format

5

My output must be "2015-02-01"

I tried to DateTime.Now.ToString("yyyy-m-d") , but it does not put the 0 between days and months.

    
asked by anonymous 04.04.2016 / 02:31

2 answers

8

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

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

Please note the capitalization. m is minute, M is month.

See working at IDEONE .


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

  • In addition to Now , UtcNow exists.

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


Following are 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:
link

    
04.04.2016 / 02:34
4

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

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

See running on dotNetFiddle .

I gave an option using the current culture that should be the most appropriate in most cases, after all it is common for the application to let the general user settings determine this and not what the programmer wants the user to see. Note that dotNetFiddle uses the American standard by default, so it gets out of hand. I also did 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 year-month-day pattern, 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, / p>     

04.04.2016 / 02:56