How to check if a Localdate is a weekend?

Asked

Viewed 2,204 times

10

I have the following date of type LocalDate

2017-12-21

How to check if it’s a weekend?

I tried to use the Calendar, but it seems to only work with Date.

4 answers

16


Just use the method getDayOfWeek(). This returns an element of enum DayOfWeek:

public static boolean fimDeSemana(LocalDate ld) {
    DayOfWeek d = ld.getDayOfWeek();
    return d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY;
}

Here’s a full test of it:

import java.time.DayOfWeek;
import java.time.LocalDate;

class Teste {

    public static boolean fimDeSemana(LocalDate ld) {
        DayOfWeek d = ld.getDayOfWeek();
        return d == DayOfWeek.SATURDAY || d == DayOfWeek.SUNDAY;
    }

    public static void main(String[] args) {
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 19))); // false, terça-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 20))); // false, quarta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 21))); // false, quinta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 22))); // false, sexta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 23))); // true, sábado
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 24))); // true, domingo
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 25))); // false, segunda-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 26))); // false, terça-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 27))); // false, quarta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 28))); // false, quinta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 29))); // false, sexta-feira
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 30))); // true, sábado
        System.out.println(fimDeSemana(LocalDate.of(2017, 12, 31))); // true, domingo
        System.out.println(fimDeSemana(LocalDate.of(2018,  1,  1))); // false, segunda-feira
    }
}

See here working on ideone.

2

To victor’s response is correct, just wanted to add another alternative.

Instead of a static method, you can also create a java.time.temporal.TemporalQuery:

// TemporalQuery que verifica se é fim de semana
TemporalQuery<Boolean> fds = t -> {
    DayOfWeek dow = DayOfWeek.from(t);
    return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
};

To use it, just use the method query:

LocalDate dt = LocalDate.of(2017, 12, 21);
boolean fimDeSemana = dt.query(fds); // false

The great advantage is that a TemporalQuery can be used with any type that implements java.time.temporal.TemporalAccessor, as an example LocalDateTime, OffsetDateTime and ZonedDateTime (and any other class that implements TemporalAccessor and have a day of the week):

boolean fimDeSemana = ZonedDateTime.now().query(fds);

You can also use it directly with a java.time.format.DateTimeFormatter, for example, if your input is a String:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/uuuu");
boolean fimDeSemana = fmt.parse("21/12/2017", fds);

Although the static method works perfectly, I think using a TemporalQuery is more flexible, for the reasons above. But of course it all depends on your use cases.


Of course, if the class in question has no day of the week, an Exception will be launched:

// lança exception porque LocalTime não tem dia da semana
LocalTime.now().query(fds);

-1

public class Horadiasdatalocalservice {

public static LocalTime horaLocal() {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("kk:mm:ss");
    CharSequence localTime = LocalTime.now().toString();


    return LocalTime.parse(localTime, dateTimeFormatter);

}

public static LocalDate dataLocal() {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        CharSequence localDate = LocalDate.now().toString();


        return LocalDate.parse(localDate, dateTimeFormatter);

    }

// MAXIMUM 3 BUSINESS DAYS BOOKING BOOK.............

public static LocalDate dataReservaLimite() {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    LocalDate localDatePlus3 = LocalDate.now().plusDays(3); 

    LocalDate localDateAnalyzed = verificarFinalDeSemana(localDatePlus3);


    return LocalDate.parse(localDateAnalyzed.toString(), dateTimeFormatter);

}

// MAXIMUM 10 WORKING DAYS TO RENT THE BOOK.............

public static LocalDate dataEmprestimoDevolucao() {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    LocalDate localDatePlus10 = LocalDate.now().plusDays(10);   

    LocalDate localDateAnalyzed = verificarFinalDeSemana(localDatePlus10);


    return LocalDate.parse(localDateAnalyzed.toString(), dateTimeFormatter);


}



public static LocalDate dataRenovacaoEmprestimo(Long idEmprestimo) {


    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    LocalDate localDatePlus10 = LocalDate.now().plusDays(10);   

    LocalDate localDateAnalyzed = verificarFinalDeSemana(localDatePlus10);


    return LocalDate.parse(localDateAnalyzed.toString(), dateTimeFormatter);


}


//"PROXIMO DIA UTIL"
private static LocalDate verificarFinalDeSemana(LocalDate dataAgendada) {

    LocalDate dataAnalyzed = dataAgendada;

    if (dataAgendada.getDayOfWeek() == DayOfWeek.SATURDAY){

        dataAnalyzed = dataAgendada.plusDays(2);

    } else if(dataAgendada.getDayOfWeek() == DayOfWeek.SUNDAY) {

        dataAnalyzed = dataAgendada.plusDays(1);

    } 
    return dataAnalyzed;


}

-4

I got it this way...

    import java.util.*;
    public class Data{
         public static void main(String[] args) {

         //Instanciando a classe Calendar juntamente com a classe GregorianCalendar
         Calendar data = new GregorianCalendar();

         //Condicação do que diz qual o dia da semana apartir da data do sistema
         switch(data.get(Calendar.DAY_OF_WEEK)){
            case 1:
                System.out.println("Domingo");
                break;
            case 2:
                System.out.println("Segunda-feira");
                break;
            case 3:
                System.out.println("Terça-feira");
                break;
            case 4:
                System.out.println("Quarta-feira");
                break;
            case 5:
                System.out.println("Quinta-feira");
                break;
            case 6:
                System.out.println("Sexta-feira");
                break;
            case 7:
                System.out.println("Sabado");
                break;
        }

        //COMPLETANDO... CASO SEJA FIM DE SEMANA OU MEIO DE SEMANA...
        if ((data.get(Calendar.DAY_OF_WEEK) == 7) || (data.get(Calendar.DAY_OF_WEEK) == 1){
            System.out.println("Fim de Semana");
        } else {
            System.out.println("Dias úteis");
        }
        System.out.println("\n\nFIM DO PROGRAMA!!!");
    } 
}

NOTE: I activate the Calendar class, so I didn’t really answer the question asked, but I did this other algorithm and it seems that it worked tmb...

import java.time.*;
public class Data{
public static void main(String[] args) {

    LocalDate data = LocalDate.now();
    DayOfWeek sabado = DayOfWeek.of(6);
    DayOfWeek domingo = DayOfWeek.of(7);

    if (data.getDayOfWeek().equals(sabado)){
        System.out.println("Fim de Semana!");
    } else if(data.getDayOfWeek().equals(domingo)) {
        System.out.println("Fim de Semana!");
    } else{
        System.out.println("Qualquer dia comum da semana!");
    }

    System.out.println("\n\nFIM DO PROGRAMA!!!");
}

}

  • 2

    Como verificar se um LocalDate é um fim-de-semana? - doubt is with Localdate, besides its code does not say when it is weekend, is not using the type questioned.

  • Apologies I thought only to specify the days, but I believe q now the question has been answered, I hope.

  • 4

    Please reread the question.

  • Damn, mate, I really did it!!! This time I did it!?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.