Categories
JavaScript Tutorials

The Date Object

Date() is a constructor function that creates date objects. 

You can create a new object by passing:

  • Nothing (defaults to today’s date)
  • A date-like string
  • Separate values for day, month, time, and so on
  • A timestamp

An object instantiated with today’s date/time:

new Date()
//Fri Mar 04 2022 16:55:52 GMT+0530 (India Standard Time)

(As with all objects, the console displays the result of the toString() method, so this long string “Fri Mar 04….” is what you get when you call toString() on a date object.)

Here are some examples of using strings to initialize a date object. It’s interesting how many different formats you can use to specify the date.

new Date('2009 11 12')
//Thu Nov 12 2009 00:00:00 GMT+0530 (India Standard Time)
new Date('1 1 2012')
//Sun Jan 01 2012 00:00:00 GMT+0530 (India Standard Time)
new Date('1 mar 2012 5:30')
//Thu Mar 01 2012 05:30:00 GMT+0530 (India Standard Time)

It is good that JavaScript can figure out a date from different strings, but this is not really a reliable way of defining a precise date. The better way is to pass numeric values to the Date() constructor representing:

  • Year
  • Month: 0 (January) to 11 (December)
  • Day: 1 to 31
  • Hour: 0 to 23
  • Minutes: 0 to 59
  • Seconds: 0 to 59
  • Milliseconds: 0 to 999

Let’s see some examples.

//Passing all the parameters:
new Date(2008, 0, 1, 17, 05, 03, 120)
//Tue Jan 01 2008 17:03 GMT+0530 (India Standard Time)

//Passing date and hour:
new Date(2008, 0, 1, 17)
//Tue Jan 01 2008 17:00:00 GMT+0530 (India Standard Time)

Methods to Work with Date Objects

Once you’ve created a date object, there are lots of methods you can call on that object. Most of the methods can be divided into set() and get() methods. For example getMonth(), setMonth(), getHours(), setHours(), and so on. Let’s see some examples.

//Creating a date object:
var d = new Date();
d.toString();
//"Wed Jan 09 2008 00:26:39 GMT+0530 (India Standard Time)"

//Setting the month to March (months start from 0):
d.setMonth(2);
1205051199562
d.toString();
//"Fri Mar 04 2022 16:55:52 GMT+0530 (India Standard Time)"

//Getting the month:
d.getMonth();
//2

In addition to all the methods of the date instances, there are also two methods that are properties of the Date() function/object. These do not need a date instance; they work just like Math’s methods. In class-based languages, such methods would be called “static” because they don’t require an instance.

//Date.parse() takes a string and returns a timestamp
Date.parse('Jan 1, 2008')
//1199174400000

//Date.UTC() takes all parameters for year, month, day, and so on, and produces a timestamp in Universal time.
Date.UTC(2008, 0, 1)
//1199145600000

Examples

Print the current date in ‘date/month/year’ format using the Date object.

var mydate = new Date();
var date = mydate.getDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log(date+"/"+month+"/"+year);

Create a digital clock that shows hours, minutes, seconds and milliseconds.

<h1 id='d1'></h1>
<script>            
	setInterval(function(){
		var d = new Date();
		var clocktime = document.getElementById('d1');
		clocktime.innerHTML = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds();
	},100);
</script>

Write a program to take the DOB of a person as input and print the current age of the person in the console.

<html>
    <input type="date" onchange="getAge(event)" id="d1">
    <script>
        function getAge(e){
            var dob = new Date(e.target.value)
            var today = new Date();
            var currentAge = (today.getTime()-dob.getTime())/(1000*60*60*24*365);
            console.log(currentAge);
        }
    </script>
</html>

Write a program to create a check-in/check-out system for employees that can show the time duration the employee was in.

<script>
	var times = [];
	var totalTime = 0;
	function checkin(){
		times.push(Date.now());
		console.log(times);
	}
	function checkout(){
		totalTime=0;
		times.push(Date.now());
		for(let i=0;i<=times.length-1;i=i+2){
			totalTime = totalTime+(times[i+1]-times[i])
		}
		document.getElementById('tt').innerHTML = totalTime/1000+"seconds"
		console.log(times);
	}
	var d1 = new Date();
	var cdate = d1.getDate();
	var cmonth = d1.getMonth();
	var cyear = d1.getFullYear();
	var el = document.getElementById('d1');
	el.innerHTML = cdate+"/"+cmonth+"/"+cyear;
	setInterval(function(){
		var d1 = new Date();
		var chours = d1.getHours();
		var cminutes = d1.getMinutes();
		var csec = d1.getSeconds();
		var el2 = document.getElementById("d2");
		el2.innerHTML = (chours<10?'0'+chours:chours)+":"+(cminutes<10?'0'+cminutes:cminutes)+":"+(csec<10?'0'+csec:csec);
	},1000)
</script>