Open9

JSchallenger にチャレンジ - Fundamentals / Dates

cyamycyamy

Check if two dates are equal

Sounds easy, but you need to know the trick
Write a function that takes two date instances as arguments
It should return true if the dates are equal
It should return false otherwise

回答

function myFunction(a, b) {   
  return a-b === 0;
}
cyamycyamy

Return the number of days between two dates

Write a function that takes two date instances as argument
It should return the number of days that lies between those dates

回答

function myFunction(a, b) {
  return Math.abs((a - b) / (24 * 60 * 60 * 1000));
}
cyamycyamy

Check if two dates fall on the exact same day

Write a function that takes two date instances as argument
It should return true if they fall on the exact same day
It should return false otherwise

回答

function myFunction(a, b) {
  return a - b === 0;
}
cyamycyamy

Check if two dates are within 1 hour from each other

Write a function that takes two date instances as argument
It should return true if the difference between the dates is less than or equal to 1 hour
It should return false otherwise

回答

function myFunction(a, b) {
 return Math.abs(a-b) <= 60 * 60 * 1000;
}
cyamycyamy

Check if one date is earlier than another

Write a function that takes two date instances (a and b) as arguments
It should return true if a is earlier than b
It should return false otherwise

回答

function myFunction(a, b) {
  return a-b < 0;
}
cyamycyamy

Add n days to an existing date

Write a function that takes as argument a date instance (a) and a number (b)
It should add b days to a and return the number of milliseconds since January 1, 1970, 00:00:00 UTC

回答

function myFunction(a, b) {
  return Date.parse(a) + (b * 24 * 60 * 60 * 1000);
}
cyamycyamy

Calculate difference between two dates in hours, minutes, and seconds

This is a more difficult challenge
Write a function that takes two date instances as arguments
It should return an object with the properties 'hrs', 'min', and 'sec'
The corresponding values should display the absolute difference between the two dates in hours, minutes, and seconds

回答

function myFunction(a, b) {
  const time = new Date(Math.abs(Date.parse(a) - Date.parse(b)));
  return {
    hrs: time.getUTCHours(),
    min: time.getUTCMinutes(),
    sec: time.getUTCSeconds()
  }
}
cyamycyamy

Return the next nearest quarter hour of a date

Write a function that takes a Date instance as argument
It should return the next nearest quarter hour in minutes
For example, if the given date has the time 10:01 the function should return 15

回答

function myFunction(date) {
  const minute = date.getUTCMinutes();
  return (minute <= 15)
    ? 15
    : (minute <= 30)
      ? 30
      :(minute <= 45) 
        ? 45 : 0;
}