Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Calculate duration using timestamps (string)

Newcomer here to the coding world.

I've written this chunk of code to calculate the time difference (duration) between two timestamps. I'm pretty happy with it. But I want to know if there is any way I can improve on what I wrote and get the same outcome.

Here's an example,


  const startTime = 2202-05-12 + "T" + 10:00:00 + "Z"
  const endTime = 2202-05-12 + "T" + 11:45:00 + "Z"

  const format_startTime = new Date(startTime);
  const format_endTime = new Date(endTime)

  const hours_startTime = format_startTime.getHours()
  const hours_endTime = format_endTime.getHours()

  const min_startTime = format_startTime.getMinutes()
  const min_endTime = format_endTime.getMinutes()

  const hours_Duration = hours_endTime - hours_startTime
  const min_Duration = min_endTime - min_startTime

  const min_Decimal = min_Duration * (1/60)

  const duration = hours_Duration + (min_Decimal === 0 ? '' : min_Decimal) + " hours";

Result - 1.75 hours

Edit 1 - to clarify, the requirement for this exercise is to use date and time in string format.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can subtract one timestamp directly from the other to get the difference in milliseconds. Your version will also only be accurate if both timestamps are on the same day.

  const startTime = "2202-05-12T10:00:00Z"
  const endTime = "2202-05-12T11:45:00Z"

  const format_startTime = new Date(startTime);
  const format_endTime = new Date(endTime);

  const differenceInMillis = format_endTime - format_startTime;
  const differenceInHours = differenceInMillis / 1000 / 60 / 60; // 1.75
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!