Playing with Javascript Date Object ( Without Moment.js ) (Part 1)


Date and time are the most integral part of our application as they play a regular role in our everyday life. We can't imagine our life without Date and Time and therefore we can't make an application without them.

Whether you create an e-commerce application or you create social networking application you will need to work with Date and Time with relevant timezone and format that is understandable in different localesAdditionally, you might need to use JavaScript Date and Time to generate a report at a certain time every day or filter them through currently open restaurants and hospitals.

So let's get started with the basic concepts first and then we are going to move to the more advanced concepts.



How can we get the Current Date?

Many times you need to get the current date and time at the client's location or at your end.
In this case, you can get the current date using new Date(). This, in turn, will return a date object. 
Example - 



format date without moment.js


How can we get Date Object from any date/ timestamp/ individual date items?


You can only use Javascript functions on Date Objects. So in order to convert your date string or timestamp into Date Object, you can make use of the new Date() function.

Example -

- From Date String


find greater than date
- From TimeStamp


change date format in javascript

- From Year,  Month, Date, Hour, Minutes, Seconds

change time format in javascript

Now that we know about Javascript Date object, let us discuss some basic Javascript Date Functions that will come handy in the latter part of the tutorial.

date comparison in javascript

change format without external library

    (Ref - www.w3school.com)


So, now we know the basics of Javascript Date Object.
Time to get started with the real things :D


1. How to convert Date into the Format you want without the use of moment.js?

Many times you need to convert date into the format you want. It's easy to do the same without the use of any external library like moment.js.
Suppose we have date "
03-04-2020" and we need to convert it to "March 04, 2020".
For this, First, we need to get the date object. You can get this with the help of new Date("03-04-2020").

Once you get the Date Object you can get the date, month, and year from the date object.
After getting the individual elements of date you can proceed in the way demonstrated in the below example with the help of replacing and simple array methodologies.



function converToDateFormat(dateToConvert,dateFormat){
    let _convertedDate;

    //Get Date Object
    let _getDateObject = new Date(dateToConvert)

    //Get Individual Date Elements
    let _dateValue = _getDateObject.getDate();
    let _monthValue = _getDateObject.getMonth();
    let _yearValue = _getDateObject.getFullYear();

    _dateValue= (_dateValue.toString().length==1?"0"+_dateValue:_dateValue);
    _monthValue = (_monthValue.toString().length==1?"0"+_monthValue:_monthValue);

    //Replace Months
    var _occurenceOfM=((dateFormat.split("m")).length - 1);
    if(_occurenceOfM==2){
       _convertedDate = dateFormat.replace("mm",_monthValue);
    } else{
       //You can change this for different language as per your need.
       let _monthArr = ["Jan","Feb","Mar","April","May","June","July","Aug","Sept","Oct","Nov","Dec"];
       _convertedDate = dateFormat.replace("mmm",_monthArr[parseInt(_monthValue)- 1]);
   }
    //Replace Date
    _convertedDate = _convertedDate.replace("dd",_dateValue);
    //Replace Year
    _convertedDate = _convertedDate.replace("yyyy",_yearValue).replace("yy",_yearValue.toString().substring(2,4));
    return _convertedDate;

}

/* This can be further modified according to needs like the month array can be modified as you need, the occurrence of single m can be handled as well if you don't want to show 0 in front of numbers less than 10 and many more.*/



2.  Using Intl.DateTimeFormat to format the date.

Recently, the Javascript team introduced Intl.DateTimeFormat object that enables us to format language-sensitive date and time.


Example using basic Intl.DateTimeFormat -


var date = new Date(2016, 11, 20, 3, 0, 0);

// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// → "11/20/2016" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)


One very useful use case of Intl.DateTimeFormat is that it can be used when our application is made for different countries and we want to convert the date according to a different locale.

Example Using Locale -


var date = new Date(Date.UTC(2020, 02, 20, 3, 0, 0));

// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)

// US English uses month-day-year order
console.log(new Intl.DateTimeFormat('en-US').format(date));
// → "3/20/2020"

// British English uses day-month-year order
console.log(new Intl.DateTimeFormat('en-GB').format(date));
// → "20/03/2020"

// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat('ko-KR').format(date));
// → "2020. 3. 20."

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat('ar-EG').format(date));
// → "٢٠‏/٣‏/٢٠٢٠"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date));
// → "R2/3/20"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian

console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// → "20/3/2020"



Intl.DateTimeFormat also supports many options that can be used for further modification/ customization. This is very useful when we want Weekday along with the date and the weekday should come in the specified locale. It can also be when we want to display the month (long) according to locale and many such cases.

Example Using Different Options -



var date = new Date(Date.UTC(2020, 02, 20, 3, 0, 0, 200));

// request a weekday along with a long date
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
// → "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// → "Thursday, December 20, 2012, GMT"

// sometimes you want to be more precise
options = {
hour: 'numeric', minute: 'numeric', second: 'numeric',
timeZone: 'Australia/Sydney',
timeZoneName: 'short'
};
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// → "2:00:00 pm AEDT"

// sometimes you want to be very precise
options.fractionalSecondDigits = 3;
console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
// → "2:00:00.200 pm AEDT"


// sometimes even the US needs 24-hour time
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
hour12: false,
timeZone: 'America/Los_Angeles'
};
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// → "12/19/2012, 19:00:00"


// to specify options but use the browser's default locale, use 'default'
console.log(new Intl.DateTimeFormat('default', options).format(date));
// → "12/19/2012, 19:00:00"


3. Using Date.toLocaleString() to format the date.


Similar to 
Intl.DateTimeFormat, Date.toLocaleString helps us to format language-sensitive date and time. Recently, locale and options were introduced in Date.toLocaleString() The new locale and options arguments let applications specify the language whose formatting conventions should be used and allow them to customize the behavior.

Example - 


const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: الخميس، ٢٠ ديسمبر، ٢٠١٢

console.log(event.toLocaleDateString(undefined, options));
// expected output: Thursday, December 20, 2012 (varies according to default locale)



Note (Performance)
When formatting large numbers of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property.

4. Using Date.toLocaleTimeString() to get Time String from Date Object

Many times, we just want to deal with the time portion of the date, in such cases, we can use Date.toLocaleTimeString(). This date object function is very helpful when we want to get the time string or when we want to convert 12 hours format to 24 hours format. The toLocaleTimeString() method returns a string with a language sensitive representation of the time portion of this date.

Example -

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US

// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('en-US'));
// → "7:00:00 PM"

// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString('en-GB'));
// → "03:00:00"

// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('ko-KR'));
// → "오후 12:00:00"

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString('ar-EG'));
// → "٧:٠٠:٠٠ م"

// an application may want to use UTC and make that visible
var options = { timeZone: 'UTC', timeZoneName: 'short' };
console.log(date.toLocaleTimeString('en-US', options));
// → "3:00:00 AM GMT"

// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString('en-US', { hour12: false }));
// → "19:00:00"

// show only hours and minutes, use options with the default locale - use an empty array
console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// → "20:01"


5. Comparing Dates.

Just like moments.js, you can compare date easily just using simple programming tricks and our very own, very special Javascript Date Object. Enough of talking let's get into the code part.

Free Tip - When dealing with Dates Conditions, it's better to convert the date object into the timestamp using Date.getTime() function.

Examples -

//check wheather date comes after current date
function isAfterDate(getDate){
if(new Date(getDate) > new Date()){
return true
}
return false
}

//check wheather date comes in between the date mentioned
function checkInBetween(firstDate,secondDate,checkBetweenDate){
if(new Date(firstDate).getTime() < new Date(secondDate).getTime() && new Date(checkBetweenDate).getTime() <= new Date(dateSecond).getTime()){
return true
}else{
return false
}
}

//check wheather date comes after current date or is same as current date
function isSameBeforeDate(getDate){
if(new Date(getDate) <= new Date()){
return true
}
return false
}

//Tip - You can use setHours(0,0,0,0) if you want to remove the impact of time in comparison




Conclusion
Javascript date Object is very usefull and have many uses. It can do everything that moment.js or any other external library gives us. In some cases when you need to reduce the size of your project and remove unwanted files. You can use you own date functions and easy Javascript Date Functions. This is just tip of IceBurg, part 2 is coming soon.



Thanks for reading, please feel free to contact us.