Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a time (not a date) using Luxon?

I need to convert backend-fetched data "17:00" to "5pm". Using moment I just do:

moment('17:00', ['HH']).format('h:mma')

How to achieve the same thing with Luxon? While moment allows to format times directly, it seems Luxon's format functions require a date (which I don't have).

Any suggestion?

like image 416
drake035 Avatar asked Oct 30 '25 17:10

drake035


1 Answers

DateTime.fromISO('17:00').toLocaleString(DateTime.TIME_SIMPLE)    // 5:00 PM
DateTime.fromISO('17:00').toFormat('h:mma')                       // 5:00PM
DateTime.fromISO('17:00').toFormat('h:mm a')                      // 5:00 PM

couldn't figure out how to make meridiem lowercase though
https://github.com/moment/luxon/issues/224

EDIT if want in lowercase can do something like this

const DateTime = luxon.DateTime;
 
const dt = DateTime.fromISO('17:00')
const meridiem = (dt.hour > 11) ? 'p' : 'a'
const final =  `${dt.toFormat('h:mm')}${meridiem}m`

console.log(final)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js"></script>

UPDATE as Lukas H. mentioned in the comments an easier approach would be to use .toLowerCase()

const DateTime = luxon.DateTime;

const dt = DateTime.fromISO('17:00')
const final =  dt.toFormat('h:mma').toLowerCase()

console.log(final)
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js"></script>
like image 104
cmgchess Avatar answered Nov 01 '25 08:11

cmgchess