Count the Days in Java

The challenge

Little Annie is very excited for upcoming events. She want’s to know how many days she have to wait for a specific event.

Your job is to help her out.

Task: Write a function which returns the number of days from today till the given date. The function will take a Date object as parameter. You have to round the amount of days.

If the event is in the past, return “The day is in the past!”
If the event is today, return “Today is the day!”
Else, return “x days”

The solution in Java code

Option 1:

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Day{

  public String countDays(Date d){
        Date now = new Date();
        if (now.equals(d)) return "Today is the day!";
        else if (now.after(d)) return "The day is in the past!";
        else return TimeUnit.DAYS.convert(d.getTime() - now.getTime(), TimeUnit.MILLISECONDS) + " days";
  }
  
}

Option 2:

import java.util.Date;
import java.time.Duration;
import java.time.Instant;

public class Day{

  public String countDays(final Date d) {
    final long diff = Duration.between(Instant.now(), d.toInstant()).toDays();
    if (diff < 0) return "The day is in the past!";
    if (diff == 0) return "Today is the day!";
    return diff + " days";
  }
}

Option 3:

import java.util.Date;

public class Day {
  static String countDays(Date d) {
    long days = (d.getTime() - System.currentTimeMillis()) / 86400000;
    return days < 0 ? "The day is in the past!" : days > 0 ? days + " days" : "Today is the day!";
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.util.Date;
import java.util.Random;

public class DayTest {
    @Test
    public void standardTests() {
        Day d = new Day();
        assertEquals("The day is in the past!", d.countDays(new Date(2000-1900,12,24))); //year 2000
        assertEquals("Today is the day!", d.countDays(new Date()));
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments