Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
989 B
4
Indexable
Never
function convertISOtoSeconds(timePeriod) {
  let timePerRegex = /P((\d+)Y)?((\d+)M)?((\d+)W)?((\d+)D)?T((\d+)H)?((\d+)M)?((\d+)S)?/;

  const extractTimes = timePerRegex.exec(timePeriod);  // extracting the year, month, day, hours, minutes and seconds
  if (!extractTimes) {
    throw new Error("Invalid ISO 8601 duration format");
}
  console.log('extractTimes:::: ', extractTimes)

  const year = Number(extractTimes?.[2]) || 0
  const month = Number(extractTimes?.[4]) || 0
  const day = Number(extractTimes?.[8]) || 0

  const yearMonthDay = year * 31536000 +
    month * 2628288 +
    day * 86400;

  const hours = Number(extractTimes?.[10]) || 0;
  const minutes = Number(extractTimes?.[12]) || 0;
  const seconds = Number(extractTimes?.[14]) || 0;

  // get total seconds now
  const totalSeconds = yearMonthDay + hours * 3600 + minutes * 60 + seconds;

  console.log(totalSeconds);
}

const durationToConvert = 'PT60M' // 60 minutes 63075600

convertISOtoSeconds(durationToConvert)