zodiac2k's Blog

Zeitperioden eines Jahres in Wochen und Monaten

Programmierung > Java

Hin und wieder muss man als Programmierer monatliche oder wöchentliche Berechnungen durchführen und man benötigt die Zeitstempel für Anfang und Ende der Zeitperioden.

Hier ein Beispiel zum berechnen der Zeitperioden eines Jahres in Wochen:
import java.util.Calendar;
import java.util.Date;
.
.
.
final Calendar cal = Calendar.getInstance();
int year = 2015;

//Calendar.WEEK_OF_YEAR needs year as reference
cal.set(Calendar.YEAR, year);

for (int week = 1; week <= cal.getActualMaximum(Calendar.WEEK_OF_YEAR); week++) {
    //start time
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Date dateStart = cal.getTime();

//end time
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);

Date dateEnd = cal.getTime();

//... }
Hier ein Beispiel zum berechnen der Zeitperioden eines Jahres in Monaten:
import java.util.Calendar;
import java.util.Date;
.
.
.
final Calendar cal = Calendar.getInstance();
int year = 2015;

for (int month = 0; month < 12; month++) {
    //start time
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Date dateStart = cal.getTime();

//end time
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);

Date dateEnd = cal.getTime();

//... }


Verfasst am 14.07.2015