Home > database >  Change date to 24 hours format in JS
Change date to 24 hours format in JS

Time:09-05

I have the following date variable : const datum = new Date("2022-09-04T22:07:56 02:00") Which gives me the date : "2022-09-04T22:07:56 02:00". I now want to format this date to look like the following : "04.9.2022 22:07:56".

I was trying to use Moment.js which worked only partly :

datum =  moment(datum, 'YYYY-M-DD hh:mm:ss').format('DD.M.YYYY hh:mm:ss')

Which gives me the following : "04.9.2022 10:07:56" this would be correct if we would use the 12 hour clock, but we are using the 24 hour clock, so I need this instead : "04.9.2022 22:07:56"

Is there a way to change that the way I need it to be ?

CodePudding user response:

Try changing 'hh' to 'HH'.

moment(new Date("2022-09-04T22:07:56 02:00"),'YYYY-M-DD HH:mm:ss').format("DD.M.YYYY HH:mm:ss")

CodePudding user response:

You may try my code:

const now = new Date("2022-09-04T22:07:56 02:00");
let options = {
        month:"2-digit",
            day:"2-digit",
            hourCycle: 'h23',
            hour: "2-digit",
            minute: "numeric",
            second: "numeric",
            year:"numeric"
        }
let result=now.toLocaleTimeString("en-GB", options);
result=result.replaceAll("/",".");
result=result.replace(",","");
console.log(result);

CodePudding user response:

You can pass the offset value to retain the input offset value

let datum = new Date("2022-09-04T22:07:56 02:00");

let offset = moment.parseZone("2022-09-04T22:07:56 02:00").utcOffset();

let finalDate = moment(datum).utcOffset(offset).format("DD.M.YYYY HH:mm:ss");
console.log(finalDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

CodePudding user response:

change hh to HH

moment(new Date("2022-09-04T22:07:56 02:00"),'YYYY-M-DD HH:mm:ss').format("DD.M.YYYY HH:mm:ss")

  • Related