简体   繁体   中英

How to convert Date as number to Date with "-"

I am fetching an API response where I got Date like this

20180224 (it is of type number)

I need to convert it in String date format like

'2018-02-24'

I am trying like

a = 20180224;
a[5] = '-';

but it does not work here

You can use replace method.

 (\d{4})(\d{2})(\d{2})
    |       |      |
   YYYY    MM     DD 
  ( G1 ) ( G2 ) ( G2 )

 let str = `20180224` let op = str.replace(/(\\d{4})(\\d{2})(\\d{2})/g, `$1-$2-$3`) console.log(op)

You can use String.replace function and some RegExp:

 var dateAsNumber = 20180224; var dateAsString = dateAsNumber.toString().replace(/(\\d{4})(\\d{2})(\\d{2})/, "$1-$2-$3"); console.log(dateAsString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM