/now
projects
ramblings
smol projects

diff days

10.11.2023 2 min read

Create a function that takes two dates and returns the number of days between the first and second date.

For each implementation, we’ll take the same approach:

  1. Place the strings into an array, and convert them into date objects
  2. Sort the array, so that the later date comes after
  3. Diff the dates somehow

We’ll start with the crystal implementation:

# crystal
def sort_dates(a, b : String) : Array(Time)
  [Time.parse(a, "%F", Time::Location::UTC), Time.parse(b, "%F", Time::Location::UTC)].sort
end

def get_days(a, b : String) : Int
  date_a, date_b = sort_dates(a, b)
  (date_b - date_a).days
end

This was the one of the more long-winded ones, becase Time.parse seems to require a location to work. There might be another way to do this, but I didn’t find it in the API.

Moving on to nim:

# nim
proc sortDays(a, b: string): seq[DateTime] =
    return @[a.parse("yyyy-MM-dd"), b.parse("yyyy-MM-dd")]

proc getDays(a, b: string): int =
    let dates = sortDays(a, b)
    (dates[1] - dates[0]).inDays

raku:

# raku
sub sort-dates(Str $a, Str $b) {
    return [$a.Date, $b.Date].sort;
}

sub get-days(Str $a, Str $b) {
    my Date @dates = sort-dates($a, $b);
    return @dates.tail - @dates.head;
}

I really like using .tail and .head for things like this. It just reads so much more nicely than @arr[0].

ts:

// typescript
function sortDays(a: string, b: string) {
  return [new Date(a), new Date(b)].sort();
}

function getDays(a: string, b: string) {
  const [dateA, dateB] = sortDays(a, b);
  const diff = Math.abs(dateB.getTime() - dateA.getTime()); // we need to call .getTime() or typescript won't allow us to subtract dates
  const diffInDays = Math.ceil(diff / (1000 * 60 * 60 * 24));
  return diffInDays;
}

My least favorite one overall. Javascript doesn’t have any nice built-in APIs, so we have to do everything manually.

Built with Astro and Tailwind 🚀