Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Get Current Date and Time in JavaScript

In this tutorial, I am going to show you how you can get the Current date and time in JavaScript. Apart from this, you will also see how you can format the date and time in JavaScript.

I will also show you how to get a current year, month, date, hours, minutes, seconds.

Get Current Date & Time in JavaScript

Date objects in JavaScript are used to work with dates and times. The JavaScript date object can be used to get year, month and date.

Creating Date Objects

In JavaScript, date objects are created with the new Date() constructor.

var d = new Date();  

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

We can use 4 variants of Date constructor to create date objects.

  • Date()
  • Date(milliseconds)
  • Date(date string)
  • Date(year, month, day, hours, minutes, seconds, milliseconds)

I am using the first one here. 

I have listed the few methods which will provide us the information from the date object.

  • getDate() – Provides day of the month values 1-31.
  • getHours() – Provides current hour between 0-23.
  • getMinutes() – Provides current minutes between 0-59.
  • getSeconds() – Provides current seconds between 0-59.
  • getMonth() – Provides current month values 0-11. Where 0 for Jan and 11 for Dec.
  • getFullYear() – Provides a current year like four digit number (yyyy).

Current Date in JavaScript

var d       =  new Date();
var date  =  d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
document.write(date);

Current Time in JavaScript

var d      = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
document.write(time);

Current Date & Time in JavaScript

We can use above both date and time to show current date and time both in Y-m-d H:i:s format.

var d     = new Date();
var date  = d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate();
var time  = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
var dateTime = date +' '+ time;
document.write(dateTime);

Output:

2020-7-8 9:20:58

Conclusion

You have learned how to get current date and time in JavaScript.

The post How to Get Current Date and Time in JavaScript appeared first on PhpCluster.



This post first appeared on Best PHP Programming Blog, Blog For PHP Developers, PHP Tutorial,PHP Blog For Beginners, please read the originial post: here

Share the post

How to Get Current Date and Time in JavaScript

×

Subscribe to Best Php Programming Blog, Blog For Php Developers, Php Tutorial,php Blog For Beginners

Get updates delivered right to your inbox!

Thank you for your subscription

×