简体   繁体   中英

Convert date range object into ISO-8601 format using moment.js

I am using this react based date range picker. It gives me a setSelectedDayRange as an object of from and to like this

from: {day: 3, month: 8, year: 2020}
to: {day: 8, month: 8, year: 2020}

I need to convert the above into the ISO-8601 format . Since I already have moment.js installed in my project, I was hoping to utilize it.

The problem is

  1. if I try to do it like

     setSelectedDayRange = moment(); let convertedDate = moment().toISOString(); console.log("setSelectedDayRange", convertedDate);

It only converts the to date.

  1. if I try to do it like

     let convertedDate = moment(setSelectedDayRange).toISOString(); console.log("setSelectedDayRange", convertedDate);

It ends up converting currentDate-1

handleDatePickerChange = (setSelectedDayRange) => {
        console.log("initializing handleDatePickerChange()");
        console.log("setSelectedDayRange", setSelectedDayRange);
        // TODO
        // convert the dates
        
        setSelectedDayRange = moment();
    
        let convertedDate = moment().toISOString();
        console.log("setSelectedDayRange", convertedDate);
    
    
        // let convertedDate = moment(setSelectedDayRange).toISOString();
        // console.log("setSelectedDayRange", convertedDate);
    
      
        this.setState({
          selectedDayRange: setSelectedDayRange,
        });
      };

Sandbox URL to mess around with it.

Ciao, if you need just to convert setSelectedDayRange to date in toISOString you could do:

let convertedDateFrom = moment(setSelectedDayRange.from).toISOString();
console.log("setSelectedDayRange", convertedDateFrom);

let convertedDateTo = moment(setSelectedDayRange.to).toISOString();
console.log("setSelectedDayRange", convertedDateTo);

Here your code modified.

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