logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



Date

dayOfYear

Gets the day of the year from a Date object.

Use new Date() and Date.prototype.getFullYear() to get the first day of the year as a Date object, subtract it from the provided date and divide with the milliseconds in each day to get the result. Use Math.floor() to appropriately round the resulting day count to an integer.

const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 272

formatDuration

Returns the human readable format of the given number of milliseconds.

Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.prototype.filter() to keep only non-zero values. Use Array.prototype.map() to create the string for each value, pluralizing appropriately. Use String.prototype.join(', ') to combine the values into a string.

const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'

getColonTimeFromDate

Returns a string of the form HH:MM:SS from a Date object.

Use Date.prototype.toTimeString() and String.prototype.slice() to get the HH:MM:SS part of a given Date object.

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // "08:38:00"

getDaysDiffBetweenDates

Returns the difference (in days) between two dates.

Calculate the difference (in days) between two Date objects.

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

getMeridiemSuffixOfInteger

Converts an integer to a suffixed string, adding am or pm based on its value.

Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.

const getMeridiemSuffixOfInteger = num =>
  num === 0 || num === 24
    ? 12 + 'am'
    : num === 12
      ? 12 + 'pm'
      : num < 12
        ? (num % 12) + 'am'
        : (num % 12) + 'pm';
getMeridiemSuffixOfInteger(0); // "12am"
getMeridiemSuffixOfInteger(11); // "11am"
getMeridiemSuffixOfInteger(13); // "1pm"
getMeridiemSuffixOfInteger(25); // "1pm"

isAfterDate

Check if a date is after another date.

Use the greater than operator (>) to check if the first date comes after the second one.

const isAfterDate = (dateA, dateB) => dateA > dateB;
isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true

isBeforeDate

Check if a date is before another date.

Use the less than operator (<) to check if the first date comes before the second one.

const isBeforeDate = (dateA, dateB) => dateA < dateB;
isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true

isSameDate

Check if a date is the same as another date.

Use Date.prototype.toISOString() and strict equality checking (===) to check if the first date is the same as the second one.

const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();
isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true

maxDate

Returns the maximum of the given dates.

Use Math.max.apply() to find the maximum date value, new Date() to convert it to a Date object.

const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));
const array = [
  new Date(2017, 4, 13),
  new Date(2018, 2, 12),
  new Date(2016, 0, 10),
  new Date(2016, 0, 9)
];
maxDate(array); // 2018-03-11T22:00:00.000Z

minDate

Returns the minimum of the given dates.

Use Math.min.apply() to find the minimum date value, new Date() to convert it to a Date object.

const minDate = (...dates) => new Date(Math.min.apply(null, ...dates));
const array = [
  new Date(2017, 4, 13),
  new Date(2018, 2, 12),
  new Date(2016, 0, 10),
  new Date(2016, 0, 9)
];
minDate(array); // 2016-01-08T22:00:00.000Z

tomorrow

Results in a string representation of tomorrow's date.

Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.

const tomorrow = (long = false) => {
  let t = new Date();
  t.setDate(t.getDate() + 1);
  const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
    t.getDate()
  ).padStart(2, '0')}`;
  return !long ? ret : `${ret}T00:00:00`;
};
tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
tomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26)