wiu753
wiu753

Reputation: 33

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.

Upvotes: 3

Views: 2814

Answers (4)

mplungjan
mplungjan

Reputation: 177950

Version 1, converting anything less than 100 to hours

const num2time = num => {
  if (num < 100) num *=100;
  const [_,hh,mm] = num.toString().match(/(\d{1,2})(\d{2})$/)
  return `${hh.padStart(2,"0")}:${mm}`
}
console.log(num2time(8));
console.log(num2time(2115));
console.log(num2time(15));
console.log(num2time("8"));
console.log(num2time("2115"));

version 2 can be used if the digits are always representing valid (h)hmm

const num2time = num => num.toString().replace(/(\d{1,2})(\d{2})$/,"$1:$2");

console.log(num2time(815));
console.log(num2time(2115));
console.log(num2time("2115"));

Upvotes: 1

tevemadar
tevemadar

Reputation: 13195

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);
  }
}

Upvotes: 0

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15831

DateFns implementation

IMHO, working on adding and removing minutes and hours is a cleaner way to manage this transform:

function formattedTime(val) {
  let helperDate; 
  if(val.length <= 2) {
   if(val > 24)return 'error';       
   helperDate = dateFns.addHours(new Date(0), val-1);   
   return dateFns.format(helperDate, 'HH:mm');
  }
  if(val.length > 2) {
   let hhmm = val.match(/.{1,2}/g);
   if(hhmm[0] > 24 || hhmm[1] > 60) return 'error';
   helperDate = dateFns.addHours(new Date(0), hhmm[0]-1);
   helperDate = dateFns.addMinutes(helperDate, hhmm[1]);
   return dateFns.format(helperDate, 'HH:mm');
  }
}

const myArr = [21, 1, 24, 2115, 815];

myArr.forEach(
  val => console.log(formattedTime(val.toString()))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"></script>

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can use the first char as hour and last char as minute, you've to pad 0 on when there is less than 4 chars.

When there is 1 or 0 char you need to pad both left and right.
When there is 2 or 3 char you only pad right.

time_str = '230'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '24'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '3'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

time_str = '78'
date = new Date('1970-01-01T' + time_str.slice(0,2).padStart(2,"0") + ':' + time_str.slice(2,4).padEnd(2,"0") + 'Z');
console.log(date)
console.log(("0" + date.getUTCHours()).slice(-2) + ":" + ("0" + date.getUTCMinutes()).slice(-2))

Upvotes: 0

Related Questions