2012-12-06 14 views
8

Jeśli mam var olddate = DateTime.Parse('05/13/2012');Ustawianie terminu na pierwszy dzień następnego miesiąca?

i chcę dostać var newdate = (the first of the month after olddate, 06/01/2012 in this case);

Co bym kod? Próbowałem ustawić miesiąc + 1, ale miesiąc nie ma ustawiacza.

+0

Twoje przykłady nie wydają się być zgodne . Czy możesz wyjaśnić, czy ma to być 6 stycznia 2013 r. Po piątym grudnia 2012 r.? – Oded

+0

@Strożony przepraszam, mam sformatowany amerykański styl daty, mm/dd/rrrr – proseidon

+1

Wykonałem edycję, więc daty nie są niejednoznaczne dla osób spoza USA. – Oded

Odpowiedz

20

Spróbuj tego:

olddate = olddate.AddMonths(1); 
DateTime newDate = new DateTime(olddate.Year, olddate.Month, 1, 
    0, 0, 0, olddate.Kind); 
+0

Edycja ninja ftw. Pamiętaj także o zachowaniu 'DateTime'' Kind'. Wiele osób go ignoruje, ale jeśli zignorujesz to, a następnie przekażesz 'DateTime' do kodu, który tego nie robi, może się zdarzyć coś niespodziewanego. –

7

To nigdy nie będzie powodować poza zasięgiem błędy i zachowa DateTime „s Kind.

dt = dt.AddMonths(1.0); 
dt = new DateTime(dt.Year, dt.Month, 1, 0, 0, 0, dt.Kind); 
2

Musisz określić miesiąc i rok słusznie, a potem ustawić 1Ş dni. Spróbuj tego:

// define the right month and year of next month. 
var tempDate = oldDate.AddMonths(1); 

// define the newDate with the nextmonth and set the day as the first day :) 
var newDate = new DateTime(tempDate.Year, tempDate.Month, 1); //create 
+0

pobili mnie to 10 sekund. Mieć uprowadzenie – Kevin

0

wiele przykładów ... wybierz swój Posion;)

var olddate = DateTime.Parse("05/12/2012"); 

int currentDay = ((DateTime)olddate).Day; 
//can always replace the while loop and just put a 1 for current day 
while(currentDay != 1) 
    currentDay--; 

var newdate = (DateTime.Parse(olddate.AddMonths(1).Month.ToString() + "/" + currentDay.ToString() + "/" + olddate.AddMonths(1).Year.ToString())); 
0

wypróbować ten prosty jednego-liner:

var olddate = DateTime.Parse("05/13/2012"); 
var newdate = olddate.AddDays(-olddate.Day + 1).AddMonths(1); 
// newdate == DateTime.Parse("06/01/2012") 
Powiązane problemy