Week.java

mail@pastecode.io avatar
unknown
java
2 years ago
2.3 kB
3
Indexable
Never
package br.gov.ce.sefaz.ceind.commons;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class Week {
    public static String getWeeks(int year) throws ParseException {
        String strDate = String.format("%d.01.01", year);
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(format.parse(strDate));
        Map<Integer, List<Date>> weeks = new HashMap<>();

        Integer week = cal.get(Calendar.WEEK_OF_YEAR);
        if (weeks.get(week) == null){
            weeks.put(week, new ArrayList<>(2));
            weeks.get(week).add(cal.getTime());
        }

        while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY){
            cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1);
        }

        week = cal.get(Calendar.WEEK_OF_YEAR);
        int lastWeek = -1;
        while (weeks.get(week) == null){
            weeks.put(week, new ArrayList<>(2));
            weeks.get(week).add(cal.getTime());


            cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - 1);
            weeks.get(week - 1).add(cal.getTime());

            cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 8);
            week = cal.get(Calendar.WEEK_OF_YEAR);
            lastWeek = Math.max(week, lastWeek);
        }

        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) - 1);
        weeks.get(lastWeek).add(cal.getTime());


        SimpleDateFormat diaMes = new SimpleDateFormat("dd/MM");

        String data = weeks.entrySet().stream().map(entry -> {
            Date firstDay = entry.getValue().get(0);
            Date lastDay = entry.getValue().get(1);
            Calendar local = Calendar.getInstance();
            local.setTime(lastDay);

            return String.format("%d,%d,%s,%s", entry.getKey(), local.get(Calendar.YEAR), diaMes.format(firstDay), diaMes.format(lastDay));
        }).collect(Collectors.joining("\n"));

        String header = "semana,ano,dataInicial,dataFinal\n";

        return header+data;
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(Week.getWeeks(2022));
    }
}