-2

I have string in this format:

var date = "2012-02-12";

I would like return the date in this format:

12.2.2012

What is the easiest way for this? I was trying

var date = new Date( "2012-02-12" ).format("dd.m.yy");

but its returning error undefined is not a function.

Incredible
  • 1,335
  • 3
  • 18
  • 39

3 Answers3

1
var string = '2012-02-12';
var string = string.replace(/-/g, ".");

This will convert 2012-02-12 to 2012.02.12

Martin
  • 96
  • 8
1

You just need to reformat the string, so in browsers that support ES5 Array methods:

'2012-02-12'.split('-').reverse().map(function(v){return Number(v)}).join('.') // 12.2.2012

However, you might want a function that is a little more efficient and works in even very old environments:

function reformatDate(s) {
  var b = s.split('-');
  return b[2] + '.' + Number(b[1]) + '.' + Number(b[0]);
}

console.log(reformatDate('2012-02-12')); // 12.2.2012

If you don't care about converting '02' to '2', then:

'2012-02-12'.split('-').reverse().join('.'); // 12.02.2012

will do the job. However, that format will be understood by most people as 12 February but some as 2 December whereas the first format is unambiguously the former.

RobG
  • 124,520
  • 28
  • 153
  • 188
0

so it seem the shortest way is this:

var protocolDate = protocolDate.substr(8,2)+"."+
                   protocolDate.substr(5,2)+"."+
                   protocolDate.substr(0,4);

Isn't it a little bit counerproductive and frustrating that you can't use native javascript function for that?

Incredible
  • 1,335
  • 3
  • 18
  • 39