0

I have this information: 2014-12-29T22:04:56.000Z

I would like to get the 2014-12-29 part of it in 12/29/2014 format.

How can I do it in javascript?

Thanks!

s.n
  • 693
  • 1
  • 9
  • 18

3 Answers3

2

You could format the date like this to get your desired formatting.

var date = new Date("2014-12-29T22:04:56.000Z");

function pad(number) {
  if (number < 10) {
    return '0' + number;
  }
  return number;
}

function formatDate() {
  return pad(date.getUTCMonth() + 1) +
    '/' + pad(date.getUTCDate()) + '/' + date.getUTCFullYear();
}
console.log(formatDate())
Sreekanth
  • 3,110
  • 10
  • 22
  • Perfect! Thank you! – s.n Nov 14 '16 at 00:15
  • There is no need to use a Date, reformatting the string is much more efficient and less problematic. – RobG Nov 14 '16 at 00:55
  • @RobG what do you mean by less problematic here? I m open to learn. – Sreekanth Nov 14 '16 at 01:46
  • Parsing of date strings with the Date constructor (or Date.parse, they are equivalent for parsing) is largely implementation dependent and really requires a proper parser (there are plenty of good ones). Even parsing of ISO 8601 has some unexpected quirks. So avoiding that (see Quagaar's answer) makes life very much simpler. ;-) – RobG Nov 15 '16 at 02:53
  • oh.. I see. Thanks for the information. – Sreekanth Nov 15 '16 at 03:35
1

You could do this using RegExp replace:

var ds = '2014-12-29T22:04:56.000Z';
console.log(ds.replace(/^(\d{4})-(\d\d)-(\d\d).+$/, '$2/$3/$1'));

Another approach would be using simple String.slice to get the required parts from the date string:

console.log(ds.slice(5, 7) + '/' + ds.slice(8, 10) + '/' + ds.slice(0, 4));
Quagaar
  • 1,257
  • 12
  • 21
0

strMDY = strISO.substring(5, 7) + "/" + strISO.substring(8, 10) + "/" + strISO.substring(0, 4)

http://www.w3schools.com/jsref/jsref_substring.asp

landru27
  • 1,654
  • 12
  • 20