Search code examples
javascriptstringdatetimedate-fns

How to convert a number to time?


I'm trying to create a function that takes a number and returns a timestamp (HH:mm) using date-fns version 1.30.1 or plain JavaScript.

What I'm trying to achieve is to help a user when entering a time. I'm using Vue.js to update the field when a user moves away from the input field. So if a user types 21 then moves away, the field would ideally update to 21:00.

Some examples would be:

21 = 21:00  
1 = 01:00  
24 = 00:00  
2115 = 21:15  

Numbers like 815 does not have to return 08:15. Numbers like 7889 should return an error.

I have tried using regex:

time = time
    .replace(/^([1-9])$/, '0$1')
    .replace(/^([0-9]{2})([0-9]+)$/, '$1:$2')
    .replace(/^24/, '00:00')

I have also tried using the parse method in date-fns but can't seem to wrap my head around how to solve this.


Solution

  • Conversion based on <100 (hours-only) and >=100 (100*hours+minutes), plus some fight with 24 and single-digit numbers (both hours and minutes):

    function num2time(num){
      var h,m="00";
      if(num<100)
        h=num;
      else {
        h=Math.floor(num/100);
        m=("0"+(num%100)).slice(-2);
      }
      h=h%24;
      return ("0"+h).slice(-2)+":"+m;
    }
    
    console.log(num2time(8));
    console.log(num2time(801));
    console.log(num2time(24));
    console.log(num2time(2401));
    console.log(num2time(2115));
    console.log(num2time("8"));
    console.log(num2time("2115"));

    Original answer, kept for the comment only, but would not handle 24 or single-digit minutes correctly:

    For example you can do a very mechanical conversion

    function num2time(num){
      if(num<10)
        t="0"+num+":00";
      else if(num<100)
        t=num+":00";
      else {
        if(num<1000)
          t="0"+Math.floor(num/100);
        else if(num<2400)
          t=Math.floor(num/100)
        else
          t="00";
        t+=":"+(num%100);
      }
      return t;
    }
    
    console.log(num2time(8));
    console.log(num2time(2115));
    console.log(num2time("8"));
    console.log(num2time("2115"));

    Example verification:

    function num2time(num){
      var h,m="00";
      if(num<100)
        h=num;
      else {
        h=Math.floor(num/100);
        m=("0"+(num%100)).slice(-2);
      }
      if(h<0 || h>24) throw "Hour must be between 0 and 24"
      if(m<0 || m>59) throw "Minute must be between 0 and 59"
      h=h%24;
      return ("0"+h).slice(-2)+":"+m;
    }
    
    var numstr=prompt("Enter time code");
    while(true) {
      try {
        console.log(num2time(numstr));
        break;
      } catch(ex) {
        numstr=prompt("Enter time code, "+numstr+" is not valid\n"+ex);
      }
    }