Home > Blockchain >  Calculate duration using timestamps (string)
Calculate duration using timestamps (string)

Time:05-12

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.

CodePudding user response:

You can use .getTime() to get the epoch milliseconds of each timestamp, which is generally easier to compare with. 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.getTime() - format_startTime.getTime();
  const differenceInHours = differenceInMillis / 1000 / 60 / 60; // 1.75
  • Related