DEV Community

Cover image for Javascript: Most used DateUtils
Kurapati Mahesh
Kurapati Mahesh

Posted on • Updated on

Javascript: Most used DateUtils

Javascript has coolest Date object which has many methods to work with date. All those methods are used to extract specific parts of date, modifies given date, supports different time conversions etc. There are many javascript libraries outside to deal with date & time like moment.js, Date-fns, Day.js etc. Not everytime we need these libraries.

Ok. Let's start.

Javascript date object will use the browser's time zone and returns the date. Like shown below:

Type in new Date(); browser console - Tue Mar 01 2022 09:52:43 GMT+0530 (India Standard Time). Don't expect the same result 😛.

Here are the util functions we need for day to day work:

getToday()

function getTodayObj() {
    return new Date();
}
// Returns date obj on which you can apply all date methods.
// > Tue Mar 01 2022 10:42:34 GMT+0530 (India Standard Time)

function getTodayString() {
    return Date();
}
// Returns Date in String format.
// > 'Tue Mar 01 2022 10:43:24 GMT+0530 (India Standard Time)'

function getTodayMilliSeconds() {
    return Date.now();
}
// > 1646111650943

function getTodayUtcString() {
    return new Date().toUTCString();
}
// > Tue, 01 Mar 2022 05:14:22 GMT

function getTodayUtcTZFormat() {
    return new Date().toISOString();
}
// > 2022-03-01T05:14:42.479Z

Enter fullscreen mode Exit fullscreen mode


javascript

getDateDifference()

Before getting into code, we need to understand few basics here.

  • When you apply +, - on date object it will be coerced to number and returns date in milliseconds.

Say, +new Date(); -> 1646112380679

  • We can create date object using new Date('date string') as well.

Say, new Date('07/10/2022'); -> Sun Jul 10 2022 00:00:00 GMT+0530 (India Standard Time) - Must provide in MM/DD/YYYY format.

  • Generally, how do we calculate milliseconds per day? - 24 (hrs) * 60 (mins) * 60 (sec) * 1000 (ms) - 86400000 ms per day.

Now, we can easily grasp what are we doing to get date difference.

const date1 = new Date('02/01/2022');
const date2 = new Date('02/28/2022');
function getDateDifference(date1, date2) {
    return (date2 - date1) / (1000 * 60 * 60 * 24);
}
// > 27
Enter fullscreen mode Exit fullscreen mode

Again, there are several cases we need to cover here:

  1. Just in case your date2 < date1 and you still want positive result then use Math.abs(getDateDifference());
  2. Hey man, I just need difference in milliseconds itself. Oh! Thatz so easy just do date2-date1.
  3. hmm, I want to the difference including time as well? Again use the same. Get your time in milliseconds with date & time and pass to that function. Done.

I don't know how to get my date & time in milliseconds. Hmm ok. Here is another Util which helps you.

getDateTimeInMilliseconds()

function getDateTimeInMilliseconds() {
    return new Date(2022, 02, 01, 00, 00, 00, 0).getTime();
}
// > 1646073000000
Enter fullscreen mode Exit fullscreen mode

getUnixTimeStamp()

It is just the getDateTimeInMilliseconds() / 1000.

function getUnixTimeStamp() {
    return new Date(2022, 02, 01, 00, 00, 00, 0).getTime() / 1000;
}
// > 1646073000
Enter fullscreen mode Exit fullscreen mode

getUTCMilliseconds()

function getUtcInMilliseconds() {
    return Date.UTC(2022, 02, 01, 00, 00, 00, 0);
}
// > 1646092800000
Enter fullscreen mode Exit fullscreen mode

getDayName()

function getDayName() {
    return new Date().toLocaleDateString('en-US', { weekday: 'short'});
}
// > Tue
Enter fullscreen mode Exit fullscreen mode

Here, toLocaleDateString(?locales, ?options) contains first param as locales - which basically represents geographical region. And, options can be { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

Also, we mentioned { weekday: 'short'} in above snippet that gives dayName as Tue where as

{ weekday: 'narrow'} - gives T
{ weekday: 'long'} - gives Tuesday

Yes, based on locale day names will change. You can provide configurable locales based on the region that application is running. navigator.language can give client language. Default value is en-US.

Again, the same in case of month names as well. So, the minor change will be instead of sending { weekday: 'short'} we need to send as { month: 'short'}. Yes, narrow, long options also applicable for month as well.

getMonthName()

function getMonthName() {
    return new Date().toLocaleDateString('en-US', { month: 'short'});
}
// > Mar
Enter fullscreen mode Exit fullscreen mode

getDateOnly()

// You can replace - with / to get in dd/mm/yyyy format
function getDateOnly() {
    const date = new Date();
    return date.getFullYear()+'-'+ (date.getMonth() + 1) + '-' + date.getDate();
}
// > 2022-3-1

// Format: mm/dd/yyyy
function getDateOnly() {
    return new Date().toLocaleDateString('en-US', {day: '2-digit', month: '2-digit', year: 'numeric'});
}
// > 03/01/2022

// Format: dd/mm/yyyy
function getDateOnly() {
    return new Date().toLocaleDateString('en-GB');
}
// > 01/03/2022

// Using localeString, format: mm/dd/yyyy
function getDateOnly() {
    return new Date().toLocaleString().split(',')[0];
}
// > 3/1/2022

// Using toISOString, format: yyyy-mm-dd
function getDateOnly() {
    return new Date().toISOString().split('T')[0];
}
// > 2022-03-01
Enter fullscreen mode Exit fullscreen mode

getTimeOnly()

function getTimeOnly() {
    const date = new Date();
    return date.getHours()+':'+ date.getMinutes() + ':' + date.getSeconds();
}
// > 17:8:46

// by default locale considered as 'en-US'
function getTimeOnly() {
    return new Date().toLocaleTimeString();
}
// > 5:10:36 PM

function getTimeOnly() {
    return new Date().toLocaleTimeString('en-GB');
}
// > 17:8:46

Enter fullscreen mode Exit fullscreen mode

You can also use above toLocaleString and toISOString to get time only same as like date only.

getTimeInHrsMins()

function getTimeInHrsMins() {
    return Intl.DateTimeFormat('en-US', { hour: "numeric", minute: "numeric", hour12: true }).format(new Date());
}
// > 6:15 PM
Enter fullscreen mode Exit fullscreen mode

getTimezoneName()

function getTimezoneName() {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
// > Asia/Calcutta 
Enter fullscreen mode Exit fullscreen mode

addDay()

function addDay() {
    const today = new Date();
    const tomorrow = new Date();
    tomorrow.setDate(today.getDate() + 1);
    return tomorrow;
}
// > Wed Mar 02 2022 18:22:40 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

subtractDay()

function subtractDay() {
    const today = new Date();
    const yesterday = new Date();
    yesterday.setDate(today.getDate() - 1);
    return yesterday;
}
// > Mon Feb 28 2022 18:23:59 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

Similarly, addMonth() & subtractMonth() works.

addMonth()

function addMonth() {
    const today = new Date();
    const nextMonthToday = new Date();
    nextMonthToday.setMonth(today.getMonth() + 1);
    return nextMonthToday;
}
Enter fullscreen mode Exit fullscreen mode

Just replace + with - in above snippet to subtract month.

So far, I came across these util functions. Comment below if you required any more functions. I would love to update this.

Thanks.


💎 Love to see your response

  1. Like - You reached here means. I think, I deserve a like.
  2. Comment - We can learn together.
  3. Share - Makes others also find this resource useful.
  4. Subscribe / Follow - to stay up to date with my daily articles.
  5. Encourage me - You can buy me a Coffee

Let's discuss further.

  1. Just DM @urstrulyvishwak
  2. Or mention
    @urstrulyvishwak

For further updates:

Follow @urstrulyvishwak

Top comments (0)