Javascript: Most used DateUtils
Tags: javascript, datetime, webdev, discuss
Published: 2022-03-01 13:09:10

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()

```javascript
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

```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.

```javascript
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
```
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`.
4. 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()
```javascript
function getDateTimeInMilliseconds() {
    return new Date(2022, 02, 01, 00, 00, 00, 0).getTime();
}
// > 1646073000000
```

## getUnixTimeStamp()
It is just the `getDateTimeInMilliseconds() / 1000`.

```javascript
function getUnixTimeStamp() {
    return new Date(2022, 02, 01, 00, 00, 00, 0).getTime() / 1000;
}
// > 1646073000
```

## getUTCMilliseconds()
```javascript
function getUtcInMilliseconds() {
    return Date.UTC(2022, 02, 01, 00, 00, 00, 0);
}
// > 1646092800000
```

## getDayName()
```javascript
function getDayName() {
    return new Date().toLocaleDateString('en-US', { weekday: 'short'});
}
// > Tue
```

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()
```javascript
function getMonthName() {
    return new Date().toLocaleDateString('en-US', { month: 'short'});
}
// > Mar
```
## getDateOnly()
```javascript
// 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
```

## getTimeOnly()

```javascript
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

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

## getTimeInHrsMins()

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

## getTimezoneName()
```javascript
function getTimezoneName() {
    return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
// > Asia/Calcutta 
```

## addDay()

```javascript
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)
```
## subtractDay()
```javascript
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)
```

Similarly, `addMonth() & subtractMonth()` works.

## addMonth()
```javascript
function addMonth() {
    const today = new Date();
    const nextMonthToday = new Date();
    nextMonthToday.setMonth(today.getMonth() + 1);
    return nextMonthToday;
}
```
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.

<hr style="border-width: 2px;border-color: #87CEEB;">
<h1> 💎 Love to see your response</h1>
<ol>
<li style="padding: 10px;font-size: 30px;"><b>Like</b> - You reached here means. I think, I deserve a like.  </li>
<li style="padding: 10px;font-size: 30px;"><b>Comment</b> - We can learn together. </li>
<li style="padding: 10px;font-size: 30px;"><b>Share</b> - Makes others also find this resource useful.</li>
<li style="padding: 10px;font-size: 30px;"><b>Subscribe / Follow</b> - to stay up to date with my daily articles. </li>
<li style="padding: 10px;font-size: 30px;"><b>Encourage me</b> - <a href="https://www.buymeacoffee.com/urstrulyvishwak" target="_blank">You can buy me a Coffee</a>
</ol>
<hr style="border-width: 2px;border-color: #87CEEB;">

<h2> Let's discuss further. </h2>

<ol style="padding: 20px;">
<li style="padding: 10px;font-size: 30px;">Just DM <br> <a href="https://twitter.com/messages/compose?recipient_id=1388837509824610314&text=Hello world"
class="twitter-dm-button" data-screen-name=“@urstrulyvishwak” data-size="large">@urstrulyvishwak</a>
</li>
<li style="padding: 10px;font-size: 30px;">
<p> Or mention <br> <a href="https://twitter.com/intent/tweet?screen_name=urstrulyvishwak&ref_src=twsrc^tfw" class="twitter-mention-button" data-size="large" data-text="Hi, Vishwak" data-related="@urstrulyvishwak" data-show-count="false">@urstrulyvishwak</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></p> </li>
</ol>

<h2> For further updates: </h2>
<a href="https://twitter.com/urstrulyvishwak?ref_src=twsrc^tfw" class="twitter-follow-button" data-size="large" data-text="Hi, Vishwak" data-related="@urstrulyvishwak" data-show-count="false">Follow @urstrulyvishwak</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>