Date class issue: Date object is set to something I have not set

I am trying to add delay to TrainTimeTable

. I have made the arrival and departure of the train using facilities Date

. When I first print out the schedule, everything shows the correct arrival and departure times. However, after adding a 30 minute delay to all Edmonton stations and beyond. Some arrival and departure times become incorrect. The delay should only increase the arrival and departure times, but it changes travel times between some cities.

I made my getters and setters like this:

/**
 * Accessor for arrival Date variable. Returns a copy of the arrival date.
 * @return - a copy of the arrival date
 */
public Date getArrivalDate()
{
    //return a copy of the original date
    return (Date) arrival.clone();
}


/**
 * Mutator for arrival date variable.
 * @param arrival - the date to set 
 */
public void setArrivalDate( Date arrival )
{
    //uses copy of Date passed in
    this.arrival = (Date) arrival.clone();
}

      

Here is my method for adding a delay I am using LinkedList

objects Station

to store the schedule:

public void delay(String Station, int minute) {
    //sequential search for Station
    //iterate through list for Station
    boolean delayPoint = false;

    //1 ) adjust time of day
    //add delay to arrival and departure date objects
    for (Station current : schedule) {
        //By checking for delay before checking for the delay city
        //we will see the delayPoint variable set while on
        //the loop is at the station right afer the delayed Station
        //if after the delay point 
        if (delayPoint) {
            //then add delay to arrive date
            Date arrivalDate = current.getArrivalDate();
            long arrivalTime = current.getArrivalDate().getTime();
            arrivalTime += minute * MIN_TO_MS;
            arrivalDate.setTime(arrivalTime);
            current.setArrivalDate(arrivalDate);
            //and add delay to depart date
            Date departDate = current.getDepartureDate();
            long departTime = current.getDepartureDate().getTime();
            departTime += minute * MIN_TO_MS;
            departDate.setTime(departTime);
            current.setDepartureDate(departDate);

        } //if the Station matches the point of delay  
        else if (current.getCity().equals(Station)) {
            //then set the boolean
            delayPoint = true;
            //and add delay to departure
            Date departDate = current.getDepartureDate();
            long departTime = current.getDepartureDate().getTime();
            departTime += minute * MIN_TO_MS;
            departDate.setTime(departTime);
            current.setDepartureDate(departDate);
        }

    }
    //2 ) adjust day of trip
}

      

Here is my result after adding a delay of 30 minutes before Edmonton departs

Please, thank you,
Ahsen Hussein.

+3


source to share


1 answer


This is one possible solution (based on java 8 and java.time api)

Station class

    public class Station {
        private long id;
        private String name;
        private Date arrivalDate;
        private Date departureDate; ....getters and setters

      

ArrayList of stations

    List<Station> myStations = Arrays.asList(
            new Station(1,"City1",new Date(),new Date()),
            new Station(2,"City2",new Date(),new Date()),
            new Station(3,"City3",new Date(),new Date()),
            new Station(4,"City4",new Date(),new Date())
    );

      

City name to find and delay time in minutes.

String cityName = "City2";
int minutes = 30;

      

Get the station that is equal to CityName (I am currently showing an alternative to the loop view)

    Station current = myStations.stream()
            .filter(s -> s.getName().equals(cityName))
            .findFirst().orElse(null);

      

The current station is equal to the city name, so you can add a delay



delay(current,minutes,false);

      

Now add a delay to the next stations (assuming the next stations have and id than the current station)

myStations.stream()
                .filter(s -> s.getId()>current.getId())
                .collect(Collectors.toList())
                .forEach(s -> delay(s,minutes,true));

      

delay method (this delay method is based on the java.time api)

public static void delay(Station current, int minutes, boolean isDelay){
    System.out.println("Current Station | Before: " + current);
    LocalDateTime stationArrival =null;
    LocalDateTime stationDeparture=null;


    if (current !=null && isDelay){
        stationArrival = getLocalDateTimeFromDate(current.getArrivalDate());
        stationDeparture = getLocalDateTimeFromDate(current.getDepartureDate());
        stationArrival=stationArrival.plusMinutes(minutes);
        stationDeparture=stationDeparture.plusMinutes(minutes);
        current.setArrivalDate(getDateFromLocalDateTime(stationArrival));
        current.setDepartureDate(getDateFromLocalDateTime(stationDeparture));
    }else if(current!=null && !isDelay){
        stationDeparture = getLocalDateTimeFromDate(current.getDepartureDate());
        stationDeparture= stationDeparture.plusMinutes(minutes);
        current.setDepartureDate(getDateFromLocalDateTime(stationDeparture));
    }

    System.out.println("Current Station | After: " + current);
}

      

helppers method for converting from Date ↔ LocaleDateTime

public static  LocalDateTime getLocalDateTimeFromDate(Date date){
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}

public static Date getDateFromLocalDateTime(LocalDateTime localDateTime){
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

      

This alternative is based on the java.time api using LocalDateTime, java.time works perfect for me. There are many conversions with java.uitl.Date that are very difficult to deal with. If you are interested in learning more about java.time, here is the Java Date Time Api tutorial .

Hope it helps.

0


source







All Articles