-3

I am working with jQuery.

I have date as August 2, 2016 format.

Now, I want to convert this date into Y-m-d format as 2016-08-02.

So, What jQuery should I have to write to resolve this problem?

Nisarg Bhavsar
  • 946
  • 2
  • 18
  • 40
  • 2
    Every conceivable JavaScript date formatting question has been asked and answered a dozen times over here on on SO (and thousands of times on the web at large). Please search before posting. – T.J. Crowder Aug 02 '16 at 07:12
  • jQuery doesn't have date-specific functions, try here: http://stackoverflow.com/questions/5250244/jquery-date-formatting – Ḟḹáḿíṅḡ Ⱬỏḿƀíé Aug 02 '16 at 07:13
  • Not an answer, but a suggestion: I really recommend checking out [moment.js](http://momentjs.com/) if you're doing a lot of work with dates. JavaScript dates/times can be quite a nightmare, moment.js makes it really easy – Brett Gregson Aug 02 '16 at 07:13

2 Answers2

1

you can use this code for Y-m-d

var date    = new Date(userDate),
yr      = date.getFullYear(),
month   = date.getMonth(),
day     = date.getDate(),
newDate = yr + '-' + month + '-' + day;
console.log(newDate);

or this for YYYY-mm-dd

var date    = new Date(userDate),
yr      = date.getFullYear(),
month   = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth(),
day     = date.getDate()  < 10 ? '0' + date.getDate()  : date.getDate(),
newDate = yr + '-' + month + '-' + day;
console.log(newDate);
shady youssery
  • 430
  • 2
  • 17
0
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]);
 };  

d = new Date();
$('#today').html(d.yyyymmdd());

check here

Ranjan
  • 929
  • 1
  • 6
  • 19