- JavaScript Basics
- JS Home
- JS Syntax
- JS Placements
- JS Output
- JS Statements
- JS Keywords
- JS Comments
- JS Variables
- JS var
- JS let
- JS const
- JS var Vs let Vs const
- JS Operators
- JS Arithmetic Operators
- JS Assignment Operators
- JS Comparison Operators
- JS Logical Operators
- JS Bitwise Operators
- JS Ternary Operator
- JS Operator Precedence
- JS Data Types
- JS typeof
- JS Conditional Statements
- JS Conditional Statement
- JS if Statement
- JS if...else Statement
- JS switch Statement
- JS Loops
- JS for Loop
- JS while Loop
- JS do...while Loop
- JS break Statement
- JS continue Statement
- JS break Vs. continue
- JavaScript Popup Boxes
- JS Dialog Box
- JS alert Box
- JS confirm Box
- JS prompt Box
- JavaScript Functions
- JS Functions
- JS setTimeout() Method
- JS setInterval() Method
- JavaScript Events
- JS Events
- JS onclick Event
- JS onload Event
- JS Mouse Events
- JS onreset Event
- JS onsubmit Event
- JavaScript Arrays
- JS Array
- JS Find Length of Array
- JS Add Elements at Beginning
- JS Add Element at End
- JS Remove First Element
- JS Remove Last Element
- JS Get First Index
- JS Get Last Index
- JS Reverse an Array
- JS Sort an Array
- JS Concatenate Arrays
- JS join()
- JS toString()
- JS from()
- JS Check if Value Exists
- JS Check if Array
- JS Slice an Array
- JS splice()
- JS find()
- JS findIndex()
- JS entries()
- JS every()
- JS fill()
- JS filter()
- JS forEach()
- JS map()
- JavaScript Strings
- JS String
- JS Length of String
- JS Convert to Lowercase
- JS Convert to Uppercase
- JS String Concatenation
- JS search()
- JS indexOf()
- JS search() Vs. indexOf()
- JS match()
- JS match() Vs. search()
- JS replace()
- JS toString()
- JS String()
- JS includes()
- JS substr()
- JS Slice String
- JS charAt()
- JS repeat()
- JS split()
- JS charCodeAt()
- JS fromCharCode()
- JS startsWith()
- JS endsWith()
- JS trim()
- JS lastIndexOf()
- JavaScript Objects
- JS Objects
- JS Boolean Object
- JavaScript Math/Number
- JS Math Object
- JS Math.abs()
- JS Math.max()
- JS Math.min()
- JS Math.pow()
- JS Math.sqrt()
- JS Math.cbrt()
- JS Math.round()
- JS Math.ceil()
- JS Math.floor()
- JS Math.trunc
- JS toFixed()
- JS toPrecision()
- JS Math.random()
- JS Math.sign()
- JS Number.isInteger()
- JS NaN
- JS Number()
- JS parseInt()
- JS parseFloat()
- JavaScript Date and Time
- JS Date and Time
- JS Date()
- JS getFullYear()
- JS getMonth()
- JS getDate()
- JS getDay()
- JS getHours()
- JS getMinutes()
- JS getSeconds()
- JS getMilliseconds()
- JS getTime()
- JS getUTCFullYear()
- JS getUTCMonth()
- JS getUTCDate()
- JS getUTCDay()
- JS getUTCHours()
- JS getUTCMinutes()
- JS getUTCSeconds()
- JS getUTCMilliseconds()
- JS toDateString()
- JS toLocaleDateString()
- JS toLocaleTimeString()
- JS toLocaleString()
- JS toUTCString()
- JS getTimezoneOffset()
- JS toISOString()
- JavaScript Browser Objects
- JS Browser Objects
- JS Window Object
- JS Navigator Object
- JS History Object
- JS Screen Object
- JS Location Object
- JavaScript Document Object
- JS Document Object Collection
- JS Document Object Properties
- JS Document Object Methods
- JS Document Object with Forms
- JavaScript DOM
- JS DOM
- JS DOM Nodes
- JS DOM Levels
- JS DOM Interfaces
- JavaScript Cookies
- JS Cookies
- JS Create/Delete Cookies
- JavaScript Regular Expression
- JS Regular Expression
- JS RegEx .
- JS RegEx \w and \W
- JS RegEx \d and \D
- JS RegEx \s and \S
- JS RegEx \b and \B
- JS RegEx \0
- JS RegEx \n
- JS RegEx \xxx
- JS RegEx \xdd
- JS RegEx Quantifiers
- JS RegEx test()
- JS RegEx lastIndex
- JS RegEx source
- JavaScript Advance
- JS Page Redirection
- JS Form Validation
- JS Validations
- JS Error Handling
- JS Exception Handling
- JS try-catch throw finally
- JS onerror Event
- JS Multimedia
- JS Animation
- JS Image Map
- JS Debugging
- JS Browser Detection
- JS Security
- JavaScript Misc
- JS innerHTML
- JS getElementById()
- JS getElementsByClassName()
- JS getElementsByName()
- JS getElementsByTagName()
- JS querySelector()
- JS querySelectorAll()
- JS document.write()
- JS console.log()
- JS instanceof
- JavaScript Programs
- JavaScript Programs
JavaScript Date and Time (with Examples/Programs)
This post is published to provide the information regarding the work with date and time in JavaScript like:
- Why do we need to learn date and time in JavaScript?
- JavaScript Date and Time Functions
- JavaScript Date and Time Programs/Codes
- JavaScript Display Date in Format of yyyy-mm-dd
- JavaScript Display Date in Format of dd-mm-yyyy
- JavaScript Display Time in Format hh:mm:ss
- JavaScript Display Time in Format hh:mm:ss AM/PM
- JavaScript Display Date and Time in Format dd-mm-yyyy hh:mm:ss AM/PM
Everytime we need to implement date and/or time in our JavaScript code, first we need to create an object of the Date() constructor. For example:
<!DOCTYPE html> <html> <body> <p id="res"></p> <script> const d = new Date(); document.getElementById("res").innerHTML = d; </script> </body> </html>
The Date() constructor creates an object (Date object) with the current date and time based on the browser's timezone.
Why do we need to learn date and time in JavaScript?
Sometime we need to implement date and/or time in our application because of the following reasons:
- to know when the post was published
- to know when the post was modified
- to know when the comment was published
- and many more
So to implement these important features to your applications, you must have at least basic awareness regarding the work with date and time in JavaScript. That is why I have created the brief tutorial on it.
JavaScript Date and Time Functions
Before starting anything regarding the work with date and time, let me first list all the JavaScript built-in methods that can be used to fetch and/or get date and/or time in JavaScript:
- getFullYear() - get the year (in the form YYYY)
- getMonth() - get the month (0-11) of a date, where 0 is for January and 11 is for December
- getDate() - get the day of the month which will be from 1 to 31
- getDay() - get the day of the week (0-6), where 0 is for Sunday and 6 is for Saturday
- getHours() - get the hour (0-23)
- getMinutes() - get the minutes (0-59) of the time
- getSeconds() - get the seconds (0-59) of the time
- getMilliseconds() - get the milliseconds (0-999)
- getTime() - get the total number of milliseconds since January 1, 1970
- getUTCFullYear() - similar to getFullYear(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCMonth() - similar to getMonth(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCDate() - similar to getDate(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCDay() - similar to getDay(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCHours() - similar to getHours(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCMinutes() - similar to getMinutes(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCSeconds() - similar to getSeconds(), except that it will be based on the Universal Time Coordinated (UTC) date
- getUTCMilliseconds() - similar to getMilliseconds(), except that it will be based on the Universal Time Coordinated (UTC) date
- toDateString() - get the date as a string
- toLocaleDateString() - get the only the date portion of the toLocaleString()
- toLocaleTimeString() - get the only the time portion of the toLocaleString()
- toLocaleString() - get the complete date using locale conventions
- toUTCString() - get the complete date as string based on UTC date
- getTimezoneOffset() - find the difference between UTC and local time
- toISOString() - get the date as string based on the ISO (International Organization for Standardization) standard
However, there are more other methods under the category of date and time in JavaScript, but I have not listed those. Because I think, these essential methods (listed above) are much enough to do all the task regarding the work with date and time in your JavaScript application(s).
JavaScript Display Date in Format yyyy-mm-dd
<!DOCTYPE html> <html> <body> <p>Today's Date: <span id="date"></span></p> <script> const d = new Date(); let yyyy = d.getFullYear(); let mm = d.getMonth() + 1; let dd = d.getDate(); if(mm<10) mm = '0' + mm; if(dd<10) dd = '0' + dd; let dt = yyyy + "-" + mm + "-" + dd; document.getElementById("date").innerHTML = dt; </script> </body> </html>
Today's Date:
Since the getMonth() method returns month's index number of the year, which is from 0 to 11, instead of 1 to 12. Therefore I've added 1 to the returned value by this method.
JavaScript Display Date in Format dd-mm-yyyy
To display the date in the format of dd-mm-yyyy, just replace the following statement from the above (previous) example or program:
let dt = yyyy + "-" + mm + "-" + dd;
with the statement given below:
let dt = dd + "-" + mm + "-" + yyyy;
JavaScript Display Time in Format hh:mm:ss
<!DOCTYPE html> <html> <body> <p>Current Time: <span id="time"></span></p> <script> const d = new Date(); let hh = d.getHours(); let mm = d.getMinutes(); let ss = d.getSeconds(); if(hh<10) hh = '0' + hh; if(mm<10) mm = '0' + mm; if(ss<10) ss = '0' + ss; let dt = hh + ":" + mm + ":" + ss; document.getElementById("time").innerHTML = dt; </script> </body> </html>
Current Time:
JavaScript Display Time in Format hh:mm:ss AM/PM
<!DOCTYPE html> <html> <body> <p>Current Time: <span id="time"></span></p> <script> const d = new Date(); let hh = d.getHours(); let mm = d.getMinutes(); let ss = d.getSeconds(); let apm = hh<12 ? 'AM' : 'PM'; hh = hh%12; if(hh<10) hh = '0' + hh; if(mm<10) mm = '0' + mm; if(ss<10) ss = '0' + ss; let dt = hh + ":" + mm + ":" + ss + ' ' + apm; document.getElementById("time").innerHTML = dt; </script> </body> </html>
Current Time:
JavaScript Display Date and Time in Format dd-mm-yyyy hh:mm:ss AM/PM
<!DOCTYPE html> <html> <body> <p>Current Date and Time: <span id="res"></span></p> <script> const d = new Date(); let yyyy = d.getFullYear(); let mn = d.getMonth() + 1; let dd = d.getDate(); let hh = d.getHours(); let mm = d.getMinutes(); let ss = d.getSeconds(); if(mn<10) mn = '0' + mn; if(dd<10) dd = '0' + dd; if(hh<10) hh = '0' + hh; if(mm<10) mm = '0' + mm; if(ss<10) ss = '0' + ss; let apm = hh<12 ? 'AM' : 'PM'; hh = hh%12; let dt = dd + "-" + mn + "-" + yyyy + " " + hh + ":" + mm + ":" + ss + ' ' + apm; document.getElementById("res").innerHTML = dt; </script> </body> </html>
Current Date and Time:
« Previous Tutorial Next Tutorial »