How to get current date in jquery?

How to get current date in jquery?

I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.


Solution 1:

Date() is not part of jQuery, it is one of JavaScript’s features.

See the documentation on Date object.

You can do it like that:

var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output = d.getFullYear() + '/' +
    (month<10 ? '0' : '') + month + '/' +
    (day<10 ? '0' : '') + day;

See this jsfiddle for a proof.

The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.

Solution 2:

If you have jQuery UI (needed for the datepicker), this would do the trick:

$.datepicker.formatDate('yy/mm/dd', new Date());

Solution 3:

jQuery is JavaScript. Use the Javascript Date Object.

var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();

Solution 4:

Using pure Javascript your can prototype your own YYYYMMDD format;

Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
  var dd  = this.getDate().toString();
  return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding

var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console

Solution 5:

In JavaScript you can get the current date and time using the Date object;

var now = new Date();

This will get the local client machine time

Related:  Javascript - How to show escape characters in a string? [duplicate]

Example for jquery LINK

If you are using jQuery DatePicker you can apply it on any textfield like this:

$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());

Solution 6:

Since the question is tagged as JQuery:

If you are also using JQuery UI you can use $.datepicker.formatDate():

$.datepicker.formatDate('yy/mm/dd', new Date());

See this demo.