how do i convert daterangepicker value to two different variable?

Issue

I have used following line to use daterangepicker in my page

<div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
        <i class="fa fa-calendar"></i>&nbsp;
            <span></span> <i class="fa fa-caret-down"></i>
</div>

when i print in my javascript part

 console.log($('#reportrange span').text())

i got output like

April 5, 2021 - April 28, 2021

How do convert above output to two different variable like startDate and endDate in 'YYYY-MM-DD' format

Solution

The first thing, store the string you get from $('#reportrange span').text() to a variable (e.g dateStr).
Then, we need to split the string by the ‘ – ‘ in the middle and convert the first and last date strings to your desired format. For that:

const getDateInFormat = (date) => {
    return [
        date.getFullYear(), ('0' + (date.getMonth() + 1)).slice(-2), ('0' + date.getDate()).slice(-2)]
    .join('-');
}

Now, we can pass the date strings.

const dateOne = getDateInFormat(new Date(dateStr.split(' - ')[0]));
const dateTwo = getDateInFormat(new Date(dateStr.split(' - ')[1]));

Answered By – sofa_maniac

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.