2012-01-08 8 views

risposta

39
string sMonth = DateTime.Now.ToString("MM"); 
+0

Che cosa succede se abbiamo bisogno di ottenere il MM per qualsiasi altro mese? –

+1

@AlokRajasukumaran someDate.ToString ("MM yyyy") –

9

Un sacco di modi diversi per farlo.

Per mantenere la semantica, vorrei utilizzare la proprietà Month del DateTime e il formato utilizzando uno dei custom numeric format strings:

DateTime.Now.Month.ToString("00"); 
0
DateTime.Now.Month.ToString("0#") 
3

uso stringa di formattazione ... la "0" è un luogo specifico -holder da visualizzare il valore atteso

DateTime.Now.Month.ToString("00") 
3
using System; 

class Program 
{ 
    static void Main() 
    { 
    // 
    // Get the current month integer. 
    // 
    DateTime now = DateTime.Now; 
    // 
    // Write the month integer and then the three-letter month. 
    // 
    Console.WriteLine(now.Month); 
    Console.WriteLine(now.ToString("MMM")); 
    } 
} 

uscita

maggio

Problemi correlati