shahid hamdam
shahid hamdam

Reputation: 821

change date format from 2017-01-11 to 01/12/2017

I am having dates in this form. Format of both dates is different. i need to compare these dates so if format is not same i cannot get anything.

  2017-01-11
  01/12/2017

I want to change format of this date 2017-01-11 in to this 01/12/2017. How can i do that?

I am trying it in this way

      var date = $(this).val();
      day  = date.getDate(),  
      month = date.getMonth() + 1,              
      year =  date.getFullYear();

     alert(year + '-' + month + '-' + day);

getting error date.getDate is not a function

Upvotes: 1

Views: 727

Answers (2)

Aminur Rashid
Aminur Rashid

Reputation: 769

There is an awesome library named Moment.js to work with dates in javascript. I've created an jsfiddle demonstrating how easy and clean your code will be with this library, sample: alert(moment('2017-01-11').isSame('01/12/2017')); You don't have to worry about date formats anymore, it will compare two date strings with different formatting. Happy coding :)

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 7004

Try this...

var d = new Date('2017-01-11');
var n = d.toLocaleDateString();
var a = n.split('/');

console.log(a);
if(a[0] <=9)
{
  a[0] = '0'+a[0];
}
if(a[1] <=9)
 {
  a[1] = '0'+a[1];
 }
var date = a.join('/');
alert(date);

See fiddle here.http://www.w3schools.com/code/tryit.asp?filename=FBH5FASDUQEI

Upvotes: 2

Related Questions