JavaScript Date

The Date object allows to work with dates (years, months, days, hours, minutes, seconds, and milliseconds)

Date Format

Default date format in string notation can be like below

or as an timestamp integer

above timestamp is Unix time, the number of seconds since 00:00:00 UTC on January 1, 1970

Display Dates

In below example, a current date is display in a <p> tag

<!DOCTYPE html>
<html>
<body>

Current Date : <span id="date"></span>
 
<script>
document.getElementById("date").innerHTML = Date();
</script>

</body>
</html>

Download the code Run the code

Create Date Object

Date object is used to work with dates

Using new Date() constructor a date object can be created.

Date can be a combination of year, month, day, hour, minute, second and millisecond.

// Creates a date object with current date
var curDate = new Date();

Syntax

new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

Parameters

value : Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC

dateString : String value representing a date.

year : Integer value that denotes year.

month : Integer value that denotes month. 0 for January to 11 for December

day : Integer value that denotes day.

hour : Integer value that denotes hour.

minute : Integer value that denotes minute.

second : Integer value that denotes second.

millisecond : Integer value that denotes millisecond.

Description

If not parameters specified than Date object create with current date and time

If two arguments are provided and day will be set to 1 and hour, minute, second value set to 0

JavaScript date object returns value based on client system settings and time zone.

<!DOCTYPE html>
<html>
<body>

If date is provided it will be displayed as follows :<br />
<span id="date"></span><br /><br />

The timezone will be taken from user's system.
 
<script>
var d = new Date("September 30, 1983 19:30:00");
document.getElementById('date').innerHTML=d;
</script>

</body>
</html>

Download the code Run the code

Date Methods

Date various methods available with date object to get and set different parameters for date

toUTCString() method used to convert date string to UTC format

<!DOCTYPE html>
<html>
<body>

Date in UTC format :<br />
<span id="date"></span><br /><br />
 
<script>
var d = new Date("September 30, 1983 19:30:00");
document.getElementById('date').innerHTML=d.toUTCString();
</script>

</body>
</html>

Download the code Run the code

toDateString() method used to convert date in readable format

<!DOCTYPE html>
<html>
<body>

Date in UTC format :<br />
<span id="date"></span><br /><br />
 
<script>
var d = new Date("September 30, 1983 19:30:00");
document.getElementById('date').innerHTML=d.toDateString();
</script>

</body>
</html>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .