-1

here i am getting a time value as 1700. I want to convert this into a format like this 5pm. I tried to do this with moment package. It has a lot of options, I'm not able to find the relevant format to achieve the output I am looking for.

Result has to be something like this:

1700 -> 5pm

0900 -> 9am

Current impl of mine is

moment("1500", "hh").format('LT') => 3:00 PM

Here the output is different, it has to be like 3pm.

Is there any way I can achieve this. Help me with your suggestions and feedback

SDK
  • 1,356
  • 3
  • 19
  • 44

2 Answers2

2

The moment().format("hA"); does what you need. See https://momentjs.com/docs/#/displaying/format/

Teun
  • 165
  • 1
  • 7
2

You do not need to use momentjs; if you are sure your input time will always be a 4-digit string, you can make your own simple formatting function (the following code is just the base concept, you might want to refine it a bit to better fit your needs):

function formatTime(str) {
  const [hh, mm] = str.match(/[0-9]{2}/g);
  const hours = parseInt(hh);
  const ampm = hours < 12 ? 'am' : 'pm';
  
  return `${hours === 12 ? hours : hours % 12}${parseInt(mm) > 0 ? `:${mm}` : ''}${ampm}`
}

// test
['1500', '0900', '1345', '0000', '1217', '1805'].forEach(item => console.log(formatTime(item)));
secan
  • 2,622
  • 1
  • 7
  • 24