JavaScript Date Objects - What are date objects in JavaScript



JavaScript Date Objects

  • JavaScript Date Objects let us work with dates.
Tue Dec 20 2022 15:46:54 GMT+0530 (India Standard Time)
javascript-date-objects

Sample Code

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>new Date() without arguments, creates a date object with the current date and time:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Output

JavaScript Dates
Using new Date()
new Date() without arguments, creates a date object with the current date and time:
Tue Dec 20 2022 15:52:32 GMT+0530 (India Standard Time)

JavaScript Date Output

  • By default, JavaScript will use the browser's time zone and display a date as a full text string.
Tue Dec 20 2022 15:46:54 GMT+0530 (India Standard Time)

Creating Date Objects

  • Date objects are created with the new Date() constructor.
  • There are 9 ways to create a new date object.
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)

JavaScript new Date()

  • new Date() creates a date object with the current date and time.
javascript-new-date

Sample Code

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>Create a new date object with the current date and time:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Output

Using new Date()
Create a new date object with the current date and time:
Fri Dec 23 2022 15:56:15 GMT+0530 (India Standard Time)

Using 6, 4, 3, or 2 Numbers

  • 6 numbers specify year, month, day, hour, minute, second.
javascipt-date-format-method

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript new Date()</h2>
<p>6 numbers specify year, month, day, hour, minute and second:</p>

<p id="demo"></p>

<script>
const d = new Date(2018, 11, 24, 10, 33, 30);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Output

JavaScript new Date()
6 numbers specify year, month, day, hour, minute and second:
Mon Dec 24 2018 10:33:30 GMT+0530 (India Standard Time)

Related Searches to JavaScript Date Objects - What are date objects in JavaScript