3

I am having a field called Duration it contains time like 00:20:40.How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds .I tried the following but didn't work.

var time = new Date('00:10:40');
  time.getMinutes();

Output will look like:

The given time is <20 minute.Hence i need to check like this

if(<20 minutes){...}
G Pandurengan
  • 129
  • 2
  • 9

3 Answers3

1

You can do the following:

var time = "00:20:40".split(":");
var minutes = time[1];

The given string "00:20:40" is not a valid date string and cannot be passed to new Date() as an argument. In this case, you can use the above solution which will split the string and give you an array consisting of [hh, mm, ss] and you will be able to get the minutes at time[1].

I hope it helps.

Ashish Patel
  • 357
  • 4
  • 15
  • 1
    I'd really not recommend working with Dates/Times on a string basis... – Jeff Sep 09 '18 at 14:41
  • 1
    You are forgetting that if it's an ISO string, this can have a LOT of problems. – weirdpanda Sep 09 '18 at 14:42
  • @Weirdpanda, Jeff, As per his question, "00:20:40" is not a standard date string. It cannot be passed to new Date(). I'm interested in knowing what kind of data it is and where he is getting this data from. – Ashish Patel Sep 09 '18 at 14:44
1

You have to create Date Object with Date to use it.

var d = new Date("1970-01-01 20:18:02");
document.write(d.getMinutes());
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Sep 09 '18 at 14:54
0
function toSeconds (duration) {
  const regex = /(\d+):(\d+):(\d+)/;
  const matched = duration.match(regex);
  const hours = parseInt(matched[1]);
  const minutes = parseInt(matched[2]);
  const seconds = parseInt(matched[3]);
  return (hours * 60 * 60) + (minutes * 60) + seconds;
}

function toMinutes (duration) {
  const seconds = toSeconds(duration);
  return seconds / 60;
}

function toHours (duration) {
  const minutes = toMinutes(duration);
  return minutes / 60;
}

toSeconds('00:20:40') // 1240
toMinutes('00:20:40') // 20.666666666666668
toMinutes('01:20:40') // 80.66666666666667
toHours('01:20:40') // 1.3444444444444446
kit
  • 535
  • 4
  • 10