Calculate the total number of seconds from an ISO8601 duration with TypeScript by utilizing the date-fns library

Given an ISO8601 duration string like "PT1M14S," I am looking to convert it to seconds as an Integer using the date-fns library in TypeScript.

Answer №1

If you are looking for a solution, you can try using the package called iso8601-duration. An example of its usage would be:

import { parse, toSeconds } from 'iso8601-duration';    
toSeconds(parse("PT1M14S"))

Have you checked if date-fns offers any similar functionality?

Answer №2

Deciphering an ISO duration poses one challenge, while applying the values to a Date presents another hurdle. Below is a straightforward parser that furnishes an object structured as {part: value} similar to this:

{year: 1, month, 3, hour: 1, minute: 2}

It solely provides attributes for tokens present in the string. However, a more robust string validation mechanism should be incorporated.

function parseISODuration(s) {

  // Quick and dirty verification of string, a more sophisticated method is required
  // Verification should involve checking tokens, order, and values
  // For instance, ensure decimals are only included in the smallest unit, and W excludes other date parts
  if (!/^P/.test(s)) return;
  
  // Segmenting into parts
  let parts = s.match(/\d+(\.\d+)?[a-z]|T/gi);

  // Indicator for date and time components to distinguish between month and minute
  let inDate = true;

  // Mapping of part tokens to corresponding names
  let partMap = {Y:'year',M:'month',W:'week',D:'day',h:'hour',m:'minute',s:'second'}
  
  return parts.reduce((acc, part) => {
  
    // Update flag upon reaching a time component
    if (part == 'T') {
      inDate = false;
      return acc;
    }
    
    // Resolve time component ambiguity (month/minute)
    if (!inDate) {
      part = part.toLowerCase();
    }
    
    // Incorporate part name and value as a numerical figure
    acc[partMap[part.slice(-1)]] = +part.slice(0,-1);
    return acc;
  }, {});
  
}

// Illustrative instances
['P1Y2M1.5D', 'P1Y3M26DT3M', 'PT3H2M4.5S', 'P6W'].forEach(duration =>
  console.log(`${duration} => ${JSON.stringify(parseISODuration(duration))}`)
);

Transforming a duration to milliseconds is a complex task and necessitates consideration of a start date context. One method involves duplicating the start date, integrating the relevant values (where a library can be beneficial), and subsequently determining the disparity between the start and end dates.

This approach factors in variations in month lengths and day durations (accounting for daylight saving time) through the Date instance and library. Nevertheless, numerous discussions with well-rounded responses are available on enhancing years, months, days, etc., to a date, thereby simplifying the creation of custom functions for such purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

The Vuetify rating system seems to be having trouble displaying

I've integrated the Vuetify rating component into my app (https://vuetifyjs.com/en/components/ratings#ratings), but I'm facing an issue. Despite having Vuetify 1.5.5 installed and working with other components like buttons, the stars in the ratin ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

Using Javascript to display an element when scrolling within a specific container and each item of an array reaches the top

I'm just starting out with JavaScript and I'm attempting to create a scrollable div that includes items from an array. As the user scrolls and each item reaches the top, I want a hidden element to be displayed. Here's what I have so far: ...

JavaScript's Math.round function does not always produce accurate results

After adding the specified line within the function, the code seems to encounter issues. parseLocalFloatCnt: num = Math.round(num*1.2); Is there a solution available for this problem? Your help is much appreciated. <!DOCTYPE html> <html> < ...

Display or conceal elements in a v-for select input by leveraging the value of another input with Vue3

In my form, I have two dropdown select option fields generated using loops from predefined constants. One dropdown is for selecting different "sides" and the other for choosing various "caps". When a user selects "2-Sided" in the sides dropdown, I want t ...

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

Retrieving subscriber count from Feedburner using jQuery and JSON

Is there a way to showcase the total number of feedburner subscribers in a standard HTML/jQuery environment without using PHP? The code snippet should be functional within a typical HTML/jQuery page. Perhaps something along these lines: $(document). ...

Generating a new POST header

I have encountered a challenge: I need to transfer an array to another page without using AJAX. My goal is to either redirect the user to the new page or open a popup displaying the new page, all while ensuring the array data is sent via a POST request. C ...

Vue.js not populating select option tags

I've encountered an issue with my profie.html code that is intended to display division dropdown values using vue.js v-for and {{ val.division_name }}. However, the dropdown is rendering blank values even though there are supposed to be values present ...

Peer-to-peer Ajax image sharing

Currently, I'm utilizing Ajax to fetch images from a remote server. Initially, I attempted this by directly using the URL of the remote server - resulting in the returned image being a string (given that's how Ajax communicates). To rectify this, ...

Tips for managing update logic in the server side with sveltekit

Currently, I am using Sveltekit and I am facing a dilemma regarding updating input data. The actual update process is straightforward, but there is an issue that arises when trying to send an update API request immediately, as it requires an accessToken to ...

Reload a tab on an ajax-enabled webpage

I am currently facing an issue with refreshing a tab instead of the entire page using Ajax. The specific tab in question involves deleting credit cards. When I select the credit card I want to delete and confirm, I use "window.location.reload();" to refres ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

Issues with creating modal images using only JavaScript

I am facing an issue with modal popup images. I have a collection of images and attempted to implement this code (with some modifications): https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img However, it seems to only work for the initi ...

Dependencies exclusively for NPM post-installUnique Rewrite: "N

I have been using git to distribute an internal TypeScript NPM package. To avoid cluttering my repository with build files, I have implemented a postinstall action to build the package upon installation: "postinstall": "tsc -p tsconfig.json& ...

A TypeScript interface creating a type with optional keys of various types while enforcing strict null checks

I am attempting to devise an interface in typescript that resembles the following: type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpe ...

Monitor modifications to a DOM element's ClientRect dimensions

I have developed a component that utilizes the context feature to register a DOM node and include it in a QuadTree. export default class SelectableGroup extends React.PureComponent { getChildContext() { return { register: this.register, ...

The property length is undefined and cannot be read

I'm currently utilizing a dexi.io robot for the purpose of automating data extraction from permit databases. This particular robot has the capability to process custom JavaScript in order to dissect the incoming JSON object. While this code does func ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...