✨♻️One line - Date Operations in JavaScript

edisonpappi

Edison Augusthy

Posted on September 14, 2020

✨♻️One line - Date Operations in JavaScript

See some of the useful single line JavaScript snippets for dealing with dates

Cheking

Is Before

Check if a date is before another date.

// 2020/10/20 is before 2020/10/21
new Date('2020/10/20') < new Date('2020/10/21');
// => true
Enter fullscreen mode Exit fullscreen mode
Is Same

Check if a date is the same as another date.

// '2020-10-20' is same of '2020-10-21'

new Date(2020, 9, 20).valueOf() === new Date(2020, 9, 21).valueOf();
// => false
new Date(2020, 9, 20).valueOf() === new Date(2020, 9, 20).valueOf();
// => true
new Date(2020, 9, 20).getTime() === new Date(2020, 9, 20).getTime();
// => true
new Date(2020, 9, 20).valueOf() === new Date(2020, 9, 20).getTime();
// => true
new Date(2020, 9, 20).toDateString().substring(4, 7) ===
  new Date(2020, 9, 21).toDateString().substring(4, 7);
// => true
Enter fullscreen mode Exit fullscreen mode
Is After

Check if a date is after another date

new Date(2020, 9, 20) > new Date(2020, 9, 19);
// => true
Enter fullscreen mode Exit fullscreen mode
Is Leap Year

Check if a year is a leap year

new Date(2000, 1, 29).getDate() === 29;
// => true
Enter fullscreen mode Exit fullscreen mode
Is a Date

Check if a variable is a native js Date object.


new Date() instanceof Date;
// => true
Enter fullscreen mode Exit fullscreen mode

Get Or Set

Get the Millisecond/Second/Minute/Hour of the given date

new Date().getSeconds();
// => 49
new Date().getHours();
// => 19
Enter fullscreen mode Exit fullscreen mode

Set the Millisecond/Second/Minute/Hour of the given date.

new Date(new Date().setSeconds(30));
// => "2020-09-09T09:12:30.695Z"
new Date(new Date().setHours(13));
// => "2020-09-09T03:12:49.695Z"
Enter fullscreen mode Exit fullscreen mode
Date of Month

Gets the day of the month.


new Date().getDate();
// => 9

Enter fullscreen mode Exit fullscreen mode

Sets the day of the month

new Date().setDate(4);
// => "2020-09-04T09:12:49.695Z"
Enter fullscreen mode Exit fullscreen mode
Day of Week

Gets the day of the week.


new Date().getDay();
// => 0 (Sunday)
Enter fullscreen mode Exit fullscreen mode

Sets the day of the week


new Date().setDate(new Date().getDate() - 14);
// => "2020-08-26T09:12:49.695Z"
Enter fullscreen mode Exit fullscreen mode
Day of Year

Gets or sets the day of the year.


Math.floor(
  (new Date() - new Date(new Date().getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24
);
// => 252
Enter fullscreen mode Exit fullscreen mode
Week of Year

Gets the week of the year

const day = new Date();
const MILLISECONDS_IN_WEEK = 604800000;
const firstDayOfWeek = 1; // monday as the first day (0 = sunday)
const startOfYear = new Date(day.getFullYear(), 0, 1);
startOfYear.setDate(
  startOfYear.getDate() + (firstDayOfWeek - (startOfYear.getDay() % 7))
);
const dayWeek = Math.round((day - startOfYear) / MILLISECONDS_IN_WEEK) + 1;
// => 37
Enter fullscreen mode Exit fullscreen mode

Sets the week of the year


const day = new Date();
const week = 24;
const MILLISECONDS_IN_WEEK = 604800000;
const firstDayOfWeek = 1; // monday as the first day (0 = sunday)
const startOfYear = new Date(day.getFullYear(), 0, 1);
startOfYear.setDate(
  startOfYear.getDate() + (firstDayOfWeek - (startOfYear.getDay() % 7))
);
const dayWeek = Math.round((day - startOfYear) / MILLISECONDS_IN_WEEK) + 1;
day.setDate(day.getDate() - (dayWeek - week) * 7);
day.toISOString();
// => "2020-06-10T09:12:49.794Z
Enter fullscreen mode Exit fullscreen mode
Days in Month

Get the number of days in the current month

new Date(2012, 02, 0).getDate();
// => 29
Enter fullscreen mode Exit fullscreen mode

Parse

Return the Date parsed from date string using the given format string

const datePattern = /^(\d{2})-(\d{2})-(\d{4})$/;
const [, month, day, year] = datePattern.exec('12-25-1995');
new Date(`${month}, ${day} ${year}`);
// => "1995-12-24T13:00:00.000Z"
Enter fullscreen mode Exit fullscreen mode

Return the Date parsed from time string using the given format string

const datePattern = /^(\d{4})-(\d{2})-(\d{2})\s(\d{1,2}):(\d{2})$/;
const [, year, month, day, rawHour, min] = datePattern.exec('2010-10-20 4:30');
new Date(`${year}-${month}-${day}T${('0' + rawHour).slice(-2)}:${min}:00`);
// => "2010-10-19T17:30:00.000Z"
Enter fullscreen mode Exit fullscreen mode

Manipulate

Add

Add the specified number of days to the given date.

// add 7 days
const now = new Date();
now.setDate(now.getDate() + 7);
// => "Sun Sep 16 2018 09:12:49"
Enter fullscreen mode Exit fullscreen mode
Subtract

Subtract the specified number of days from the given date.

// subsctact 7 days
new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7);
// => Sun Sep 09 2018 09:12:49
Enter fullscreen mode Exit fullscreen mode
End of Time

Return the end of a unit of time for the given date.

const end = new Date();
end.setHours(23, 59, 59, 999);
end.toISOString();
// => "2018-09-09T16:59:59.999Z"
Enter fullscreen mode Exit fullscreen mode

Display

Time from now

Return time from now.


new Intl.RelativeTimeFormat().format(-4, 'day');
// => "4 days ago"
Enter fullscreen mode Exit fullscreen mode
Difference

Get the unit of time between the given dates


// difference betwwen '2007-01-27' to '2007-01-29'
new Date(2007, 0, 27) - new Date(2007, 0, 29);
// => -172800000
Math.ceil(
  (new Date(2007, 0, 27) - new Date(2007, 0, 29)) / 1000 / 60 / 60 / 24
);
// => -2
Enter fullscreen mode Exit fullscreen mode

💖 💪 🙅 🚩
edisonpappi
Edison Augusthy

Posted on September 14, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related