date-fns format time in 24 hour format
Asked Answered
G

2

11

I'm using date-fns in a React project.

const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'hh:mm')

This returns '06:49'. How can I get this to return '18:49' instead?

Goldstone answered 7/10, 2021 at 2:52 Comment(2)
date-fns.org/v2.25.0/docs/format. Try HH:mmLaaland
sampleText.substring(16,21) or as local time new Date('Tue Aug 03 2021 18:49:11 GMT+0800').toLocaleString('en',{hour:'2-digit', minute:'2-digit', hour12:false}). Oh sorry, no library…Osgood
L
20

The format tokens for date-fns can be found here: https://date-fns.org/v2.28.0/docs/format

const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'HH:mm')
Laaland answered 7/10, 2021 at 2:58 Comment(0)
C
3

This is also another option which uses 'kk:mm:ss' format:

const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'kk:mm:ss')
Carbonyl answered 11/2, 2023 at 15:42 Comment(2)
What does that add to the initial answer? Also, the question specifically asked for HH:mm.Cystoscope
This is actually the correct answer. You just have to remove the ss from the format. See the documentation referenced above.Columbuscolumbyne

© 2022 - 2025 — McMap. All rights reserved.