javascripttimestamp

PThhHmmMssS date format to timespent


I need to translate this format "PThhHmmMssS" (PT7H45M26.75S) to timestamp. Is there way to do this using moment.js

I looked for solutions in the forums but found nothing. I don't understand what standard this format is based on. It would be fantastic if you could help me unravel this mystery.


Solution

  • The format "PThhHmmMssS" is one of the ISO 8601 duration formats, an international standard for representing dates, times, and durations.

    "PT" indicates that it's a time duration. "7H" represents 7 hours. "45M" represents 45 minutes. "26.75S" represents 26.75 seconds, so you have 7 hours, 45 minutes, 26.75 seconds.

    Note the different outputs in the examples below. Luxon returns ISO and the other example a JS date object

    Luxon has support

    const parseAndAddDuration = (durationString) => {
      try {
        const { Duration, DateTime } = luxon;
        const duration = Duration.fromISO(durationString);
        const currentDate = DateTime.local();
        const newDate = currentDate.plus(duration);
        return newDate.toISO();
      } catch (error) {
        throw new Error('Invalid duration format');
      }
    };
    
    // Example usage:
    const durationString = "PT7H45M26.75S";
    const newDate = parseAndAddDuration(durationString);
    console.log("New Date:", newDate);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.1.1/luxon.min.js"></script>


    There is a tinyduration package that was updated recently (June 2023)


    vanilla JS parsing

    You do not need moment which is deprecated and no longer maintained) or any other library unless you have more uses for it. Just a regex and some date manipulation

    const regex = /P(?:T(\d+)H)?(\d+)M(?:(\d+(?:\.\d+)?)S)?/;
    
    function parseAndAddDurationToCurrentDate(durationString) {
      const match = regex.exec(durationString);
    
      const hours = match[1] ? parseInt(match[1]) : 0;
      const minutes = match[2] ? parseInt(match[2]) : 0; // Use ternary operator for minutes
      const seconds = match[3] ? parseFloat(match[3]) : 0; // Handle optional seconds
      const totalSeconds = hours * 3600 + minutes * 60 + seconds;
    
    
      const currentDate = new Date();
    
      currentDate.setSeconds(currentDate.getSeconds() + totalSeconds)
      return currentDate.toISOString();
    }
    
    
    // Example usage:
    let durationString = "PT7H45M26.75S";
    let newDate = parseAndAddDurationToCurrentDate(durationString);
    
    console.log("New Date:", newDate);
    
    
    durationString = "PT16H30M";
    newDate = parseAndAddDurationToCurrentDate(durationString);
    
    console.log("New Date:", newDate);