Date manipulation

I’m stuggling to do some date manipulaion. I need to stipulate 2 dates, get the difference between them and then subtract that difference from today’s date.

I’ve done this in JavaScript, but in K6 I’m having issues with the date format.

Any advice? Appreciated.

Hello!

Could you show us what you’ve tried, please?

I’ve tried a few things , this is an example of getting the difference in days:

function difference(date1, date2) {  
  const date1utc = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
  const date2utc = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
   const day = 1000 * 60 * 60 * 24;
  return(date2utc - date1utc)/day
}

const date1 = new Date("1973-08-31"),
      date2 = new Date("2017-03-24"),
      diffdays = difference(date1,date2)

console.log(diffdays)

The dates in question span a daylight saving time change, so to get around this we need to convert the dates to UTC to get rid of the DST first then get the difference between them.

This works fine now. Returns 15911.

So it’s the last Step i’m struggling with. I need to subtract the number of days (diffdays) from today and get a date with dd/mm/yyyy format.

If today is 19/03/2021 the answer I’m looking for is 26/08/1977.

Update

day = 1000 * 60 *60 * 24
date3 = Date.now() - ( day * diffdays) 

returns the correct unix time, so I need to convert that to dd/mm/yyyy

So I’ve managed it, but this seems quite long-winded.

This code appeared to yield the expected result (if I compare the output with this):

export default function () {
  const date1 = new Date("1973-08-31"),
    date2 = new Date("2017-03-24");

  const diffdays = difference(date1, date2);

  console.log(diffdays);

  const now = new Date();
  const diffFromToday = new Date(now.setDate(now.getDate() - diffdays));

  console.log(`Date ${diffdays} days ago: ${diffFromToday.toLocaleString()}`);
}

function difference(date1, date2) {
  const date1utc = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate());
  const date2utc = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const day = 1000 * 60 * 60 * 24;
  return (date2utc - date1utc) / day
}

I maked some extension like pet project, maybe in this extension rnow() function it’s what you need.
But is not official extension))) and i didn’t use it in my job projects yet. But you can tried.

1 Like