简体   繁体   中英

How can I convert a date coming in as YYYYMMDD into MM/DD/YYYY or MM/D/YYYY depending on its length

I am getting a response back from an API and need to pass that response into another API header in a different format.

From the first api I am getting a date as YYYYMMDD and I need to pass it as a header in the format MM/DD/YYYY .

Some conditions are, if the day is a single digit (1-9) it should be converted into this format MM/D/YYYY . If the day is a double digit, it should be in this format MM/DD/YYYY .

2 examples would be:

  • the length for the date is 7, 1999101 should be converted to 10/1/1999
  • the length for the date is 8, 19991020 should be converted to 10/20/1999

I cannot use moment js.

How can I achieve this?

If you wanted to do this natively without using a library it's pretty trivial also:

function convertDate(input) {
    var year = input.substring(0, 4);
    var month = input.substring(4, 6);
    var day = input.substring(6);

    return month + "/" + day + "/" + year;
}

With that function to get the date you'd run:

var date = convertDate("1999101"); // "10/1/1999"

You can use Moment.js library for fast and easy conversion of the data.

Like

var date = moment("19991020", "YYYYMMDD");
date.format("MM/DD/YYYY"); // 10/20/1999 

For further details please check Moment.js

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