-2

Input 13.09.2018 (dd.mm.yy)

Expected format 13/09/2018 (dd/mm/yy)

How to convert the input date to expected format in javascript?

Suvethan Nantha
  • 2,404
  • 16
  • 28
  • 2
    There are a lot of answers covering this. Did none of them help you? – Luca Kiebel Sep 11 '18 at 11:24
  • 1
    you can refer this thread https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – ashish singh Sep 11 '18 at 11:24
  • if you only want to edit a string instead of a Date-Object you could use replace e.g. '13.09.2018'.replace(/./g, '/'); – Steve Kirsch Sep 11 '18 at 11:25
  • @LucaKiebel I have localization added in my asp.net core application. I have a jquery datepicker which displays data according to locale but when I set the selected date to model I got null as output – Suvethan Nantha Sep 11 '18 at 11:25
  • Can't you set desired date format in this datepicker? I'm not sure whether it's datepicker you're using, but the one I've found has option [dateFormat](http://api.jqueryui.com/datepicker/#option-dateFormat) – barbsan Sep 11 '18 at 11:45

4 Answers4

3

if your object is Date :

the fast way that you can do this is here , if you don't want use another lib :

var newDate = new Date();
newDate.toLocaleDateString('en-GB', {
     year: 'numeric',
     month: '2-digit',
     day: '2-digit'
}).replace(/\./g, '/')

result is : "11/09/2018"

and if you have a string , use this regex :

"13.09.2018".replace(/\./g,'/')

result is : "13/09/2018"

Neo Anderson
  • 638
  • 1
  • 4
  • 17
  • "if your object is Date" a quick and dirty solution would be newDate.toJSON().slice(0,10).split('-').reverse().join('/') – Joerg Veigel May 25 '22 at 09:09
2

Use date.replace(/\./g, '/') to globally replace the dot(.) with forward slash.

var date = '13.09.2018';
date = date.replace(/\./g, '/');
console.log(date);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0
var date = '13.09.2018';
console.log(date.split('.').join("/"));
pixellab
  • 588
  • 3
  • 12
0

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily get use of this, you can write something like this:

 String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
   return this.replace(new RegExp(string, 'g'), replaced);
 };

and simply use it in your code over and over like below:

 var str = "13.09.2018";
 var res = str.replaceAll(".", "/"); 
Leena Patel
  • 2,423
  • 1
  • 14
  • 28