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

Recommended Resource - JavaScript: The Hard Parts

Take your JavaScript to the next level. Gain an understanding of callbacks, higher order functions, closure, asynchronous and object-oriented JavaScript!

isWeekday

Results in a boolean representation of a specific date.

Pass the specific date object firstly. Use Date.getDay() to check weekday by using a modulo operator and then returning a boolean.

const isWeekday = (t = new Date()) => {
  return t.getDay() % 6 !== 0;
};
isWeekday(); // true (if current date is 2019-07-19)

isWeekend

Results in a boolean representation of a specific date.

Pass the specific date object firstly. Use Date.getDay() to check weekend based on the day being returned as 0 - 6 using a modulo operation then return a boolean.

const isWeekend = (t = new Date()) => {
  return t.getDay() % 6 === 0;
};
isWeekend(); // 2018-10-19 (if current date is 2018-10-18)

maxDate

Returns the maximum of the given dates.

Use the ES6 spread syntax with Math.max to find the maximum date value, new Date() to convert it to a Date object.

const maxDate = dates => new Date(Math.max(...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 the ES6 spread syntax to find the minimum date value, new Date() to convert it to a Date object.

const minDate = dates => new Date(Math.min(...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 the current date, increment by one using Date.getDate() and set the value to the result using Date.setDate(). Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

const tomorrow = () => {
  let t = new Date();
  t.setDate(t.getDate() + 1);
  return t.toISOString().split('T')[0];
};
tomorrow(); // 2018-10-19 (if current date is 2018-10-18)

yesterday

Results in a string representation of yesterday's date.

Use new Date() to get the current date, decrement by one using Date.getDate() and set the value to the result using Date.setDate(). Use Date.prototype.toISOString() to return a string in yyyy-mm-dd format.

const yesterday = () => {
  let t = new Date();
  t.setDate(t.getDate() - 1);
  return t.toISOString().split('T')[0];
};
yesterday(); // 2018-10-17 (if current date is 2018-10-18)