Date object in javascript, is used to get current date time and also allows to creates or sets date time. Date is a static object. Javascript allows to pass year, month, day, hour, minutes, seconds and milliseconds as parameters in Date() constructor.

Javascript counts date in milliseconds, since January 01, 1970.

Get current date time

Javascript provide Date() constructor to get current date time.

<script>
let d =  new Date();
document.write(d);
</script>

In above example, new Date() create a date object and gives current date and time as per web browser time zone.

How to Create or Set date

Javascript provides 9 different ways to create or set date time.

new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)
Date constructor parametersDescription or use
YearFull year should be used. e,g. 2024, 2025
MonthRepresents month.
First month starts with 0 and last month is 11.
0 means January and 11 means December.
DayRepresents Date.
hoursRepresents hour in 24 hour format.
minutesRepresents minute.
secondsRepresents seconds
millisecondsRepresents milliseconds
date stringDate should be passed in string format
e.g.
“20-10-2024”
“October 17, 2024 03:20:00”

Create or set Date javascript

Date or time can be set or created by passing year, month, day, hours, minute, second and millisecond as parameter.

new Date(date string)

Date can be passed as string in Date() object.

<script>
let d =  new Date("20-10-2024");
document.write(d);
</script>

Date and Time can be passed as string as parameters in Date() object.

<script>
let d =  new Date("October 17, 2024 03:20:00");
document.write(d);
</script>

new Date(year,month)

Only Year and month are passes as parameters in Date()

<script>
let d =  new Date(2024, 10);
document.write(d);
</script>

new Date(year,month,day,hours,minutes,seconds)

<script>
let d =  new Date(2024, 10,5,2,5,10);
document.write(d);
</script>

new Date(milliseconds)

<script>
let d =  new Date(221212);
document.write(d);
</script>

Convert Date to String in javascript

javascript provides toString() method to convert date or any type into string format.

<script>
let d =  new Date(221212);
document.write(d.toString());
</script>

Date Methods

Javascript also provides different methods to work with date time.

MethodsUse
new Date()Create a new date object.
getDate()Get current day of month
getDay()Gives day of the week from (0-6)
getHours()Get hours in 24 hour format (0-23)
getMinutes()Returns minute from 0 – 59.