0

I have to format this date yyyy-mm-dd('2019-05-31') to m/dd/yy('5/31/19').

I have tried this

var format = function(input) {
  var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
  if (!input || !input.match(pattern)) {
    return null;
  }
  return input.replace(pattern, '$2/$3/$1');
};

console.log(format('2019-05-31'));

But cannot eliminate the values.

Andreas
  • 21,535
  • 7
  • 47
  • 56
Amal
  • 212
  • 2
  • 9

3 Answers3

3

try this

function formate(yyyyMMdd) {
  const [yyyy, MM, dd] = yyyyMMdd.split('-')
  // +dd is equal to Number.parseInt(dd, 10)
  return `${Number.parseInt(MM, 10)}/${+dd}/${yyyy.slice(2)}`
}
console.log(formate('2020-08-01')); // 8/1/20
console.log(formate('2020-11-21')); // 11/21/20
console.log(formate('1019-05-31')); // 5/31/19
JackChouMine
  • 947
  • 8
  • 22
2

you can try this

function convertDate(d){
  c=d.split("-")
  d=c[1].charAt(0)==0?c[1].charAt(1):c[1]
  m=c[2].charAt(0)==0?c[2].charAt(1):c[2]
  y=c[0].charAt(2)+c[0].charAt(3)
  return d+'/'+ m +'/'+y
}
console.log(convertDate("2019-05-31"))
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
-1

Simply try this:

function format(strDate) {

    let [y, m, d] = strDate.split('-');

    date = (m - '0') + "/" + (d - '0') + "/" + y.slice(-2);

    return date;

}

console.log(format('2019-05-31'));
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
  • _"I have to format this date `yyyy-mm-dd('2019-05-31')`..."_ – Andreas Jul 01 '20 at 08:19
  • I didn't notice it carefully, updated my answer. Thanks @Andreas. – Shahnawaz Hossan Jul 01 '20 at 08:23
  • @Andreas, what's the problem in my answer? – Shahnawaz Hossan Jul 01 '20 at 08:54
  • `format()` doesn't return anything. And parsing the date first might work but also might result in a different date/output. – Andreas Jul 01 '20 at 09:56
  • It's giving the proper output, please check this. And I've added return in function. – Shahnawaz Hossan Jul 01 '20 at 09:59
  • 1
    _"Note: **Parsing of date strings with the `Date` constructor (and `Date.parse()`, which works the same way) is strongly discouraged** due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local."_ (Source: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date)) – Andreas Jul 01 '20 at 10:07
  • Hi @Andreas, I think it's ok now. Isn't it? – Shahnawaz Hossan Jul 01 '20 at 14:57
  • Why `- '0'`? That's a quite complicated way to parse the string as number. `parseInt()` or unary `+` or `~~` or ... would do the same (and would be more obvious imho) – Andreas Jul 01 '20 at 15:05
  • There are four ways to do that I think, parseInt, Number constructor, Unary and mathematical function(subtraction). I just use the last one since others are given in the others' answers. – Shahnawaz Hossan Jul 01 '20 at 15:12