How to Check If a Date Is Weekend in Java

Here are simple and reliable ways to check whether a date falls on a weekend in Java. Prefer the modern java.time API (Java 8+), which is clearer and thread-safe.

  • Using LocalDate (recommended)
import java.time.DayOfWeek;
import java.time.LocalDate;

public class WeekendChecker {
    public static boolean isWeekend(LocalDate date) {
        DayOfWeek dow = date.getDayOfWeek();
        return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
    }

    public static void main(String[] args) {
        System.out.println(isWeekend(LocalDate.now())); // true or false
    }
}
  • With time zones (e.g., when you start from an Instant)
import java.time.*;

public class WeekendCheckerTZ {
    public static boolean isWeekend(Instant instant, ZoneId zone) {
        DayOfWeek dow = instant.atZone(zone).getDayOfWeek();
        return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
    }

    public static void main(String[] args) {
        boolean weekendInNY = isWeekend(Instant.now(), ZoneId.of("America/New_York"));
        System.out.println(weekendInNY);
    }
}
  • If you still use the legacy Calendar API
import java.util.Calendar;

public class WeekendCheckerLegacy {
    public static boolean isWeekend(Calendar cal) {
        int dow = cal.get(Calendar.DAY_OF_WEEK);
        return dow == Calendar.SATURDAY || dow == Calendar.SUNDAY;
    }
}
  • Configurable “weekend” definition (some regions consider Friday/Saturday)
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.EnumSet;
import java.util.Set;

public class ConfigurableWeekend {
    private static final Set<DayOfWeek> DEFAULT_WEEKEND = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);

    public static boolean isWeekend(LocalDate date, Set<DayOfWeek> weekendDays) {
        return weekendDays.contains(date.getDayOfWeek());
    }

    public static void main(String[] args) {
        System.out.println(isWeekend(LocalDate.now(), DEFAULT_WEEKEND));
        // Example for Fri/Sat weekend:
        Set<DayOfWeek> friSatWeekend = EnumSet.of(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY);
        System.out.println(isWeekend(LocalDate.now(), friSatWeekend));
    }
}

Notes:

  • Use java.time classes (LocalDate, ZonedDateTime, DayOfWeek) for new code.
  • If you have a timestamp without a zone (Instant), convert with a ZoneId before checking the day of the week.

How to Convert Between Date and LocalDateTime

In Java, you can convert between java.util.Date and java.time.LocalDateTime using the java.time API introduced in Java 8. Here’s how you can perform the conversions:


1. Converting Date to LocalDateTime

You need to use java.time.Instant and java.time.ZoneId to make this conversion. Here’s the process:

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateToLocalDateTimeExample {
    public static void main(String[] args) {
        // Create a Date object
        Date date = new Date();

        // Convert Date to LocalDateTime
        LocalDateTime localDateTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        System.out.println("Date: " + date);
        System.out.println("LocalDateTime: " + localDateTime);
    }
}

2. Converting LocalDateTime to Date

To convert back from LocalDateTime to Date, again you will make use of Instant and ZoneId.

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateTimeToDateExample {
    public static void main(String[] args) {
        // Create a LocalDateTime object
        LocalDateTime localDateTime = LocalDateTime.now();

        // Convert LocalDateTime to Date
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        System.out.println("LocalDateTime: " + localDateTime);
        System.out.println("Date: " + date);
    }
}

Explanation:

  1. Date to LocalDateTime:
    • Date.toInstant() converts the Date object into an Instant (a specific point in time).
    • .atZone(ZoneId.systemDefault()) adjusts the instant to your system’s default time zone.
    • .toLocalDateTime() converts the zoned date-time to a LocalDateTime.
  2. LocalDateTime to Date:
    • .atZone(ZoneId.systemDefault()) converts a LocalDateTime into a ZonedDateTime.
    • ZonedDateTime.toInstant() gets an Instant for the given date and time in the local zone.
    • Date.from(Instant) creates a Date object from the Instant.

By using these conversions, you can easily switch between the old java.util.Date and the modern java.time.LocalDateTime API.

How to Calculate Date Differences Using ChronoUnit

You can calculate date differences in Java using the ChronoUnit enum from the java.time package. The ChronoUnit class is used to measure the amount of time between two temporal objects (e.g., LocalDate, LocalDateTime, etc.) in terms of specific time units like DAYS, MONTHS, YEARS, etc.

Here’s an example of how to calculate the difference between two LocalDate objects in various time units:

Example Code

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DateDifferenceExample {
    public static void main(String[] args) {
        // Define two dates
        LocalDate date1 = LocalDate.of(2023, 1, 1);
        LocalDate date2 = LocalDate.of(2025, 8, 7);

        // Calculate differences using ChronoUnit
        long daysBetween = ChronoUnit.DAYS.between(date1, date2);
        long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
        long yearsBetween = ChronoUnit.YEARS.between(date1, date2);

        // Print results
        System.out.println("Days between: " + daysBetween);
        System.out.println("Months between: " + monthsBetween);
        System.out.println("Years between: " + yearsBetween);
    }
}

Output

Days between: 949
Months between: 31
Years between: 2

Explanation

  1. between() Method:
    • The ChronoUnit.between() method takes two temporal objects as parameters and returns the difference in the specified unit (e.g., days, months, or years).
    • Ensure that the objects provided are compatible (e.g., both are LocalDate or LocalDateTime).
  2. Units of Measurement:
    • The ChronoUnit enum provides different constants such as DAYS, HOURS, WEEKS, MONTHS, YEARS, etc., to calculate differences at the desired granularity.
  3. Signed Differences:
    • The result may be negative if the first date is later than the second date. You can swap the dates if you want an absolute difference.

Other Temporal Types

ChronoUnit also works with other temporal types such as LocalDateTime, ZonedDateTime, Instant, etc. For example:

package org.kodejava.datetime;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeDifference {
    public static void main(String[] args) {
        LocalDateTime dateTime1 = LocalDateTime.of(2023, 1, 1, 10, 0);
        LocalDateTime dateTime2 = LocalDateTime.of(2025, 8, 7, 12, 30);

        long hoursBetween = ChronoUnit.HOURS.between(dateTime1, dateTime2);
        long minutesBetween = ChronoUnit.MINUTES.between(dateTime1, dateTime2);

        System.out.println("Hours between: " + hoursBetween);
        System.out.println("Minutes between: " + minutesBetween);
    }
}

This will give you the time differences in hours and minutes.

Note

  • ChronoUnit.WEEKS may not align perfectly with ChronoUnit.DAYS due to week boundaries.
  • Always validate whether the specific ChronoUnit applies to the temporal objects you’re comparing (e.g., you can’t use HOURS on LocalDate because it lacks time information).

How to Read Binary Files into Byte Arrays

To read a binary file into a byte array in Java, you can use various ways such as Files.readAllBytes(), FileInputStream, or DataInputStream. Below is an explanation of the most common methods.


Using Files.readAllBytes() (Java NIO)

This is the simplest and most efficient way if you’re using Java 7 or later. The Files.readAllBytes() method reads all the bytes from a file into a byte array.

package org.kodejava.nio;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class BinaryFileToByteArray {
    public static void main(String[] args) {
        Path filePath = Paths.get("path/to/file.bin");
        try {
            byte[] fileBytes = Files.readAllBytes(filePath);
            System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using FileInputStream

Another common way is to use FileInputStream in combination with a buffer.

package org.kodejava.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class BinaryFileToByteArray {
    public static void main(String[] args) {
        File file = new File("path/to/file.bin");
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] fileBytes = new byte[(int) file.length()];
            fis.read(fileBytes); // Read file into byte array
            System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using DataInputStream

Using DataInputStream with a FileInputStream allows you to work with primitive types and is useful when dealing with binary files.

package org.kodejava.nio;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class BinaryFileToByteArrayExam3 {
    public static void main(String[] args) {
        File file = new File("path/to/file.bin");
        try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
            byte[] fileBytes = new byte[(int) file.length()];
            dis.readFully(fileBytes); // Reads the file fully into byte array
            System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Choosing a Method

  • Files.readAllBytes is the easiest and most concise for modern Java.
  • FileInputStream and DataInputStream provide more flexibility if you need finer control over the file reading process.

Note: Always handle exceptions properly, especially in cases where the file may not exist or the application might not have the necessary permissions.

How to Create Class Diagrams with PlantUML for Clear Object-Oriented Design

PlantUML is a powerful tool to create class diagrams that help in visualizing and designing object-oriented software. Below is a comprehensive guide to creating class diagrams with PlantUML for clear object-oriented design.

1. What is PlantUML?

PlantUML is a text-based tool for creating UML (Unified Modeling Language) diagrams. It uses simple plain-text descriptions to generate visual representations of UML diagrams (including class diagrams, sequence diagrams, etc.).

2. Setting Up PlantUML

Option 1: Standalone

  1. Install Java. PlantUML requires Java (minimum version 1.8).
  2. Download the PlantUML JAR file from PlantUML’s official website.
  3. Use a text editor to write PlantUML code.
  4. Generate diagrams by running:
    java -jar plantuml.jar your-diagram-file.puml
    

Option 2: IntelliJ IDEA Integration

  1. Install the PlantUML Integration plugin in IntelliJ IDEA:
    • Go to File > Settings > Plugins.
    • Search for “PlantUML Integration”.
    • Install the plugin and restart IntelliJ IDEA.
  2. Write .puml files directly in IntelliJ and render diagrams using the integrated PlantUML viewer.

3. Components of a PlantUML Class Diagram

Basic Syntax

PlantUML class diagrams are defined inside @startuml and @enduml tags. Here’s an example:

@startuml
class ClassName {
    + PublicAttribute
    - PrivateAttribute
    # ProtectedAttribute
    + method(): ReturnType
}
@enduml

Key Elements

Symbol Meaning
+ Public
- Private
# Protected
< and > Generics/Parameterized Class
.. or -- Relationships/Dependencies

4. Example of a Class Diagram

Below is an example of modeling an object-oriented system with PlantUML:

@startuml
class Person {
    - id: int
    + name: String
    + email: String
    + getContactInfo(): String
}

class Employee {
    - employeeId: int
    + department: String
    + getRole(): String
}

class Manager {
    + manages: List<Employee>
    + assignTask(task: Task): void
}

Person <|-- Employee
Employee <|-- Manager
@enduml


Key Explanation:

  1. Class Definitions:
    • Each class (e.g., Person, Employee, Manager) is defined with attributes and methods.
  2. Inheritance:
    • The arrow <|-- shows inheritance relationships (e.g., Employee is derived from Person).
  3. Associations:
    • Use arrows (e.g., associations to depict relationships between objects).

5. Advanced Features

Adding Interfaces

@startuml
interface PaymentProcessor {
    + processPayment(amount: Double): Boolean
}

class CreditCardPayment {
    + creditCardNumber: String
    + expiryDate: String
}

PaymentProcessor <|.. CreditCardPayment
@enduml
  • You can define an interface using the interface keyword.
  • Use <|.. to implement interfaces.

Abstract Classes

@startuml
abstract class Shape {
    + draw(): void
}

class Circle {
    + radius: Double
}

class Rectangle {
    + width: Double
    + height: Double
}

Shape <|-- Circle
Shape <|-- Rectangle
@enduml
  • Define abstract classes using the abstract keyword.
  • Use <|-- to show that classes inherit from the abstract class.

Relationships

Type Syntax Example
Inheritance < | --or`<
Composition *--> or *-- House *--> Room
Aggregation o--> or o-- Team o--> Player
Association -- or <..> Library -- Borrower

Generic Classes

@startuml
class Stack<T> {
    + push(item: T): void
    + pop(): T
}
@enduml
  • Generics are supported using angle brackets (<T>).

6. Best Practices for Clear Diagrams

  1. Keep It Simple: Focus on key parts of the design. Avoid overcrowding diagrams with unnecessary details.
  2. Use Annotations: Add comments and notes to improve readability. You can annotate using:
    note "This is a general note" as N1
    
  3. Organize Classes: Use packages or group related classes together:
    package "Model" {
       class User
       class Role
    }
    
  4. Use Relationships Effectively: Clearly specify inheritance, associations, aggregations, and compositions for better understanding.

7. Generate the Diagram

After writing the .puml file, generate the diagram:

By following these steps, you can create clear, well-structured class diagrams to visualize object-oriented designs effectively.