Any easier way to write this code?

${(hour > 12) ? (hour % 12 < 10) ? '0' + hour % 12 : hour % 12 : (hour === 0) ? '12' : (hour < 10) ? '0' + hour : hour}

I wrote this line of code inside a template literal block, so I can’t put empty spaces or that breaks the whole html page. I had to use a lot of comments because honestly this code has become somewhat incomprehensible to me.
Any form of help is appreciated :hugs:

If I disentangled that correctly, you are converting 24 hour time to a 12 hour time that pads 1-9 with a zero?

If so, I think that using JS methods is easier to read than nested ternaries.

`${(hour % 12 === 0) ? 12 : (hour % 12).toString().padStart(2, '0')}`

If you like chained ternaries better (and just changing your hour variable outside the template isn’t possible) this is a bit less insane.

`${(hour % 12 === 0) ? 12 : (hour % 12 < 10) ? '0'+ (hour % 12) : (hour % 12)}`
1 Like