2009-09-29 3 views

risposta

95

Qualcosa di simile (non testata):

DateTime date; 
int quarterNumber = (date.Month-1)/3+1; 
DateTime firstDayOfQuarter = new DateTime(date.Year, (quarterNumber-1)*3+1,1); 
DateTime lastDayOfQuarter = firstDayOfQuarter.AddMonths(3).AddDays(-1); 
+0

Può spiegare che cosa il vostro codice fa? – roosteronacid

+2

@roosteronacid: '(quarterNumber-1) * 3 + 1' fornirà il numero del mese del primo mese del trimestre specificato. Il codice crea un 'DateTime' per il primo giorno di quel mese dell'anno. Questo è il primo giorno del trimestre. Quindi aggiunge tre mesi. Quello sarà il primo giorno del * prossimo * quarto, quindi l'ultimo giorno del quarto desiderato sarà il giorno prima ('.AddDays (-1)' fa questo trucco). –

+0

Vedere @il_guru answer here => http://stackoverflow.com/questions/11154673/get-the-correct-week-number-of-a-given-date – mynkow

5
int GetQuarterName(DateTime myDate) 
{ 
    return (int)Math.Ceiling(myDate.Month/3.0); 
} 

DateTime GetQuarterStartingDate(DateTime myDate) 
{ 
    return new DateTime(myDate.Year,(3*GetQuarterName(myDate))-2,1); 
} 

GetQuarterName ottiene il "prossimo" valore intero del mese in corso/numero 3.

GetQuarterStartingDate utilizza l'output di GetQuarterName a lavorare fuori il valore del mese, la parte dell'anno della data originale e 1 per rappresentare il primo giorno del mese da restituire.

(Ci scusiamo per fare non ha senso, non ho l'influenza. :()

2
 var date = new DateTime(2015, 3, 15); 

     var quarter = (date.Month + 2)/3; 

     var quarterStartMonth = 3 * quarter - 2; 

     var quarterStartDate = new DateTime(date.Year, quarterStartMonth, 1); 
0

A due di linea più semplice con demo live here + premere F8 a correre

var date = DateTime.Now; //Give you own DateTime 
int offset = 2, monthsInQtr = 3; 

var quarter = (date.Month + offset)/monthsInQtr; //To find which quarter 
var totalMonths = quarter * monthsInQtr; 

var startDateInQtr = new DateTime(date.Year, totalMonths - offset, 1); //start date in quarter 

Se siete alla ricerca di ultimo giorno dell'uso quarto DateTime.DaysInMonth

var endDateInQtr = new DateTime(date.Year, totalMonths, DateTime.DaysInMonth(date.Year, totalMonths));