MamiMrl
MamiMrl

Reputation: 33

Date calculation method for Java

I have a delivery project which consists the class names below:

FoodItem
Location
Route
Store
Vehicle
Warehouse
Launcher(Includes main method)

What I need to do next is: I have initialized an object called "Oatmeal" for the FoodItem class.

This FoodItem has 4 attributes as follows:

import java.time.LocalDate;

public class FoodItem {
    public String label;
    private double volume;
    private double weight;
    private LocalDate expirationDate;

The values for those attributes have been set in Launcher as follows:

FoodItem oatmeal = new FoodItem("Serving size is 1/2 Cup 40gr");
oatmeal.setVolume(25);
oatmeal.setWeight(0.500);
oatmeal.setExpirationDate(LocalDate.of(2025,2,5));

Now what I need to do is calculate the date to check if the product's expiration date is still valid with the logic of (Expiration Date - Today's Date + 3 Days) For that I've created a method called stillValid as follows:

import java.time.Period;
import java.util.Arrays;
import java.time.LocalDate;

private boolean stillValid(FoodItem foodItem){
        LocalDate date = LocalDate.now();
        LocalDate dayLeft = date.plus(Period.ofDays(3));
        if(foodItem.getExpirationDate() != dayLeft) {
            return true;
        }
        return false;
    }

Now I need to use this method inside of my addItem method in order to check if the Item's expiration date is not passed, I can add to the store.

public void addItem(FoodItem foodItem) { 
        int stop = 0;
        for (int i = 0; i < foodItemsArray.length; i++) {
            if (foodItemsArray[i] != null) {        
                stop = 1;
                break;
            }
        }
        if (stop == 0) {
            for (int i = 0; i < foodItemsArray.length; i++) {
                if (foodItemsArray[i] != foodItem) {
                    foodItemsArray[i] = foodItem;
                    break;
                }
            }
        }
    }

In this part, I couldn't create the logic in my mind to have my stillValid fuction inside of addItem body, or even if I did the method stillValid correct.

Upvotes: 2

Views: 280

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338276

tl;dr

Peruse the LocalDate Javadoc to discover handy methods, such as isAfter and plusDays.

LocalDate.now().isAfter( this.getExpirationDate().plusDays( 3 ) ) ;

Details

Add a stillValid or expired method to your FoodItem class, if that is the reasonable place to know the rule of adding three days to expiration date.

For comparing LocalDate, use isAfter and isBefore.

public boolean expired ()
{
    LocalDate today = LocalDate.now() ;  // Consider specifying a time zone here.
    Period gracePeriod = Period.ofDays( 3 ) ;
    LocalDate finalExpiration = this.getExpirationDate().plus( gracePeriod ) ;
    boolean isExpired = today.isAfter( finalExpiration ) ;
    return isExpired ;
}

Or, more simply:

public boolean expired ()
{
    return LocalDate.now().isAfter( this.getExpirationDate().plusDays( 3 ) ) ;
}

Usage:

if( ! foodItem.expired() ) { myList.add( foodItem ) ; }

Caveat: Note that for any given moment, the date varies around the globe by time zone. Right now it is “tomorrow” in Tokyo, Japan while still “yesterday” in Toronto, Canada. By omitting the ZoneId argument when calling LocalDate.now, your results will vary depending on the deployment JVM’s current default time zone. As suggested in the comment, consider using LocalDate#now( ZoneId zone ) e.g. LocalDate.now( ZoneId.of( "America/New_York" ) ).

Full example class

Here is an example class using the records feature new in Java 16.

package work.basil.demo;

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.util.Objects;

public record FoodItem(String label , double volume , double weight , LocalDate expirationDate , Period gracePeriod)
{
    // Constructor.
    public FoodItem ( final String label , final double volume , final double weight , final LocalDate expirationDate , final Period gracePeriod )
    {
        this.label = Objects.requireNonNull( label );
        this.volume = Objects.requireNonNull( volume );
        this.weight = Objects.requireNonNull( weight );
        this.expirationDate = Objects.requireNonNull( expirationDate );
        this.gracePeriod = Objects.requireNonNull( gracePeriod );
        if ( this.gracePeriod.isNegative() ) { throw new IllegalArgumentException( "The grace period must be positive. Message # f511c804-db04-4783-8329-3a8e928b98cf." ); }
    }

    // Calculated value. 
    public boolean isExpired ( )
    {
        return LocalDate.now().isAfter( this.expirationDate().plus( this.gracePeriod ) );
    }
}

Usage.

FoodItem oats = new FoodItem( "Oats" , 25d , 0.500d , LocalDate.of( 2025 , Month.FEBRUARY , 5 ) , Period.ofDays( 3 ) );
System.out.println( "oats = " + oats );
System.out.println( "Is oats expired: " + oats.isExpired() );

When run.

oats = FoodItem[label=Oats, volume=25.0, weight=0.5, expirationDate=2025-02-05, gracePeriod=P3D]
Is oats expired: false

Upvotes: 5

Related Questions