Java / Python / PHP / Golang / Swift/ Ruby 如何判断周六和周日周末

我们经常需要根据日期来判断是否为周末或者特定的周几。在本文中,我们将使用多种编程语言(Java、Golang、Python、Ruby、Swift、PHP)来演示如何通过编程获得和判断周六和周末日期。

Java

          
  import java.time.DayOfWeek;
  import java.time.LocalDate;
  
  public class WeekendChecker {
      public static void main(String[] args) {
          LocalDate date = LocalDate.now();
          DayOfWeek dayOfWeek = date.getDayOfWeek();
  
          if (dayOfWeek == DayOfWeek.SATURDAY) {
              System.out.println("Today is Saturday!");
          } else if (dayOfWeek == DayOfWeek.SUNDAY) {
              System.out.println("Today is Sunday!");
          } else {
              System.out.println("Today is not a weekend day.");
          }
      }
  }

    

Golang

          
    package main
  
    import (
      "fmt"
      "time"
    )
    
    func main() {
      date := time.Now()
      dayOfWeek := date.Weekday()
    
      if dayOfWeek == time.Saturday {
        fmt.Println("Today is Saturday!")
      } else if dayOfWeek == time.Sunday {
        fmt.Println("Today is Sunday!")
      } else {
        fmt.Println("Today is not a weekend day.")
      }
    }  
  
    

PHP

          
  $dayOfWeek = date('N');

  if ($dayOfWeek == 6) {  // Saturday
      echo "Today is Saturday!";
  } else if ($dayOfWeek == 7) {  // Sunday
      echo "Today is Sunday!";
  } else {
      echo "Today is not a weekend day.";
  }
  
  

Swift

          
  import Foundation
  
  let date = Date()
  let calendar = Calendar.current
  let dayOfWeek = calendar.component(.weekday, from: date)
  
  if dayOfWeek == 7 {  // Saturday
      print("Today is Saturday!")
  } else if dayOfWeek == 1 {  // Sunday
      print("Today is Sunday!")
  } else {
      print("Today is not a weekend day.")
  }

  

Ruby

          
  require 'date'
  
  date = Date.today
  day_of_week = date.wday
  
  if day_of_week == 6  # Saturday
      puts "Today is Saturday!"
  elsif day_of_week == 0  # Sunday
      puts "Today is Sunday!"
  else
      puts "Today is not a weekend day."
  end

  

Python

          
  import datetime
  
  date = datetime.date.today()
  day_of_week = date.weekday()
  
  if day_of_week == 5:  # Saturday
      print("Today is Saturday!")
  elif day_of_week == 6:  # Sunday
      print("Today is Sunday!")
  else:
      print("Today is not a weekend day.")
  
  
🇨🇳中国节假日 API