简体   繁体   English

如何使用“-”将日期作为数字转换为日期

[英]How to convert Date as number to Date with "-"

I am fetching an API response where I got Date like this我正在获取一个 API 响应,在那里我得到了这样的日期

20180224 (it is of type number) 20180224(类型编号)

I need to convert it in String date format like我需要将它转换为字符串日期格式,如

'2018-02-24' '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:您可以使用String.replace函数和一些 RegExp:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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