Home > Blockchain >  JavaScript - converting Date to UTC and removing days from it
JavaScript - converting Date to UTC and removing days from it

Time:12-22

Trying to iterate backwards from today to August, and log out all the time stamps stored on our database between those periods.

The API only allows queries between a 24 hour window, hence my need for a for loop to call it multiple times. The query’s start and end times are in ISOstring format.

Problem is, when my loop reaches October 31st, it tries to query with startTime 23:00 endTime 00:00 and complains that this is beyond the 24 hour range limit. This makes sense, as I’m from UK and this is when the clocks go back.

Is there a way for me to set my date to UTC and continuously subtract days from it, hence ignoring timezone and any daylight saving?

Our team has consistently used date-fns, so I would love a solution using this library if a library is recommended/required.

This is what I'm currently working with:

export async function dataTrawl(): Promise<void> {
    try {
        for (let date = new Date(); date >= new Date('2022-10-01'); date.setDate(date.getDate() - 1)) {
            const startTime = new Date(date.getTime());
            startTime.setDate(date.getDate() - 1);
            
            const response: AxiosResponse<DataExchangeResponse> = await axios.get(
                '...api.../1/datapoints',
                {
                    headers: {
                        accept: 'application/json',
                        'x-api-key': 'KEY'
                    },
                    params: {
                        start: startTime.toISOString(),
                        end: date.toISOString()
                    }
                }
            );
            console.log(`dataTrawl: ${JSON.stringify(response.data)}`);
        }
    } catch (e) {
        const error = e as AxiosError;
        console.error(error);
    }
}

CodePudding user response:

You can use the getUTCDate() and setUTCDate() functions to move a date backwards by one day in UTC.

This way we'll be dealing with 24 hour periods consistently with no changes due to DST rules.

export async function dataTrawl(): Promise<void> {
    try {
        const start = new Date();
        const end = new Date('2022-10-01');
        console.log(`dataTrawl: start: ${start.toISOString()} -> end: ${end.toISOString()}`);
        for (let date = start; date >= end; date.setUTCDate(date.getUTCDate() - 1)) {
            const startTime = new Date(date);
            startTime.setDate(date.getUTCDate() - 1);
            
            const response: AxiosResponse<DataExchangeResponse> = await axios.get(
                '...api.../1/datapoints',
                {
                    headers: {
                        accept: 'application/json',
                        'x-api-key': 'KEY'
                    },
                    params: {
                        start: startTime.toISOString(),
                        end: date.toISOString()
                    }
                }
            );
            console.log(`dataTrawl: ${JSON.stringify(response.data)}`);
        }
    } catch (e) {
        const error = e as AxiosError;
        console.error(error);
    }
}

CodePudding user response:

You can work in UTC days, where (in ECMAScript) every day is exactly 8.64e7 ms long:

// Set start to end of current UTC date
let start  = new Date();
start.setUTCHours(24,0,0,0);

// Loop over all previous UTC days until limit
for (let limit = new Date('2022-11-21'); start > limit; start.setTime( start - 8.64e7)) {
  let end = new Date(start - 8.64e7);
  
  // stuff with start and end
  console.log(`${start.toISOString()} -`,
              `${end.toISOString()}`); 
}

  • Related