vero
vero

Reputation: 1015

Check if Day is Saturday or Sunday

I'm looking to do a difference between 2 date in scala. These 2 date are should not saturday not sunday. I did a scala function to test if the day if Saturday or Sunday:

I edited my question, this is my code to test if a day is saturday or sunday. I should use it using tow dates : start_date and finish_date, because after this operation I'll do the difference between these tow dates. My function jourouvree took one parameter, not a dates. How can I modify my code to pass the tow dates.

Upvotes: 0

Views: 5125

Answers (2)

jwvh
jwvh

Reputation: 51271

Check if Day is Saturday or Sunday:

import java.time.{LocalDate, DayOfWeek}

def isWeekend(day: LocalDate) =
  day.getDayOfWeek == DayOfWeek.SATURDAY ||
    day.getDayOfWeek == DayOfWeek.SUNDAY

Upvotes: 2

sujit
sujit

Reputation: 2328

Using Java 8 datetime api:

import java.time._
import java.time.format.DateTimeFormatter

val formatter =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
//Assume d2,d2 themselves are not weekend days
def jourOuvree(sd1:String, sd2:String): Unit = {
    val d1 = LocalDateTime.parse(sd1, formatter)
    val d2 = LocalDateTime.parse(sd2, formatter)
    //return if d1 is not earlier than d2. TODO: handle what to be done
    if(d2.isAfter(d1) == false) return
    var (days, dayCtr) = (1, 1)
    while(d1.plusDays(dayCtr).isBefore(d2)){
        dayCtr+=1
        val dow = d1.plusDays(dayCtr).getDayOfWeek()
        if(!dow.equals(DayOfWeek.SATURDAY) && !dow.equals(DayOfWeek.SUNDAY))
            days+=1
    }
    println(days)
}

Invoke as below:

jourOuvree("2011-03-31 07:55:00", "2011-04-06 15:41:00")

You get 5 printed.

NOTE: The code doesn't handle exceptions in parsing. Also, there may be other requirement fine points, for which you are the best judge to make required changes.

Upvotes: 1

Related Questions