-4

Is there a way to filter out the seconds in javascript of a timestring and only parse them when they are not :00 ?

Like 12:00:00 should be parsed as 12:00 Like 12:00:01 should be parsed as 12:00:01

Fabb
  • 21
  • 5
  • 2
    Use an if statement? – Andrew Li Nov 08 '17 at 21:03
  • 1
    Where is your attempt? – jmargolisvt Nov 08 '17 at 21:03
  • Would help if you showed what you are currently doing.... – epascarello Nov 08 '17 at 21:03
  • The attemt is to format is without seconds when they are 00 as I get a datestring with seconds, mostly with 00 for some places where I display them without the seconds. – Fabb Nov 08 '17 at 21:09
  • @Fabb Right, but where's the code that you have? We need an example of what it is you want it to do and what you've tried or are trying. You didn't give us a base to start from. You wouldn't go to your mechanic without your car and tell them there's a problem of some sort when you drive it. – zfrisch Nov 08 '17 at 21:11
  • True, I'm searching for a way and tried to enter and add the following link where I can accross as a start. I'm just looking for a way, that an ifstatement is needed is quite clear. https://stackoverflow.com/questions/35758963/remove-seconds-milliseconds-from-date-convert-to-iso-string – Fabb Nov 08 '17 at 21:16

1 Answers1

0

If you would put this in a function, I think it'll work fine:

var d = new Date(); //get date

h = d.getHours(); //get hours, minutes and seconds
m = d.getMinutes();
s = d.getSeconds();

if (h < 10) {  // In case an hour, a minute or a second is less than 10 (so 1 decimal),
  h = "0" + h; // an extra '0' will be added.
}
if (m < 10) {
  m = "0" + m;
}
if (s < 10) {
  s = "0" + s;
}

if (s == 0) { // If 'seconds' is equal to zero, it'll only return the hours and minutes.
  return(h + ":" + m);
} else {
  return(h + ":" + m + ":" + s);
}

It's long, I know, I'm sure there are shorter versions of this.

Sacha
  • 819
  • 9
  • 27
  • Yes this very usefull, I came accross the something like same at the moment on w3schools. as it's all client side I wondered if there was something more JS or whatever library based way that doesn't rely on the browser. Your way is supported in all browsers tho – Fabb Nov 08 '17 at 21:48
  • @Fabb Glad I helped you :) – Sacha Nov 08 '17 at 21:50