-2

I have got a problem with converting Saturday, 24th December 2016 to 24/12/2016 but having a problem. My code is:

var fullDate = new Date("Saturday, 24th December 2016");

console.log(fullDate);

var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);

console.log(twoDigitMonth);

Can anyone help me?

qqruza
  • 1,385
  • 4
  • 20
  • 41
  • [Java != JavaScript](http://stackoverflow.com/a/245069) – Pshemo Nov 24 '16 at 21:51
  • I would say, use the right tool for the job. In this particular case not sure how jquery can help. But I do know a tool that was designed for such, moment.js.. http://momentjs.com/ – Keith Nov 24 '16 at 21:57
  • I am trying to do it with momentjs: var str = moment('Saturday, 24th December 2016').format('DD/MM/YYYY'); But it says Invalid Date – qqruza Nov 24 '16 at 22:11
  • Because `new Date()` accept param that `Data.parse()` returns. `Saturday, 24th December 2016` is not the standard format. You can use like this `2016/11/24` – tomision Nov 25 '16 at 01:52

2 Answers2

1

If your using momentjs, no need for all your split, and replace.

Just do ->

var 
  theDate = 'Saturday, 24th December 2016',
  fmt = 'dddd, Do MMMM YYYY';
    
var decodeDate = moment(theDate, fmt);

console.log(theDate);
console.log(decodeDate.format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.0/moment.min.js"></script>
Keith
  • 22,005
  • 2
  • 27
  • 44
0

My solution was:

var d = "Saturday, 24th December 2016";
nwd = d.split(",").pop();
date = nwd.replace(/(\d+)(st|nd|rd|th)/, "$1");
var str = moment(date).format('DD/MM/YYYY');

Please use if you have the same problem.

qqruza
  • 1,385
  • 4
  • 20
  • 41