Change Time format

Viewed 104

I have a time string and I want to convert it to have : between the hour and minutes. Any suggestions on how to take the sting and change it. I’m assuming I need to use regular expression but not sure how to format that code. Any suggestions would be great.

var number = '1340';
moment(number).format('hh:mm')
console.log(number)
// The output I want would be 13:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

5 Answers

Stick a : before the last 2 digits. This makes the assumption that your minutes are padded with zeroes if not 2 digits long:

console.log('1340'.replace(/\d{2}$/, m => ':' + m));

First off, in the code you show you are outputing the original string not the result from moment.js.

If you want to use moment, you'll need to tell it what format your string is:

var number = '1340';
var time = moment(number, 'hhmm').format('hh:mm')
console.log(time)

    var number = '1340';
    console.log(number.slice(0, 2)+":"+number.slice(2));

Moment needs a date.

You want something like this

const pad = num => ("00"+num).slice(-2);
const hhmm = str => {
  const mm = str.slice(-2)
  const hh = str.slice(0,-2)
  return `${pad(hh)}:${pad(mm)}`;
};

console.log(hhmm('1340'))
console.log(hhmm('340'))
console.log(hhmm('40'))
console.log(hhmm('0'))
console.log(hhmm(''))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

const number = "1340";
const time = `${number.substring(0,2)}:${number.substring(2,4)}`;
console.log(time);

Related