My datetime string is of below format:
var sdt = '2022-05-19T13:00:00';
I want to extract the date and time separately and below is my code:
((sdt.getMonth() > 8) ? (sdt.getMonth() + 1) : ('0' + (sdt.getMonth() + 1))) + '/' + ((sdt.getDate() > 9) ? sdt.getDate() : ('0' + sdt.getDate())) + '/' + sdt.getFullYear() + ' ' + (sdt.getHours()) + ':' + (sdt.getMinutes()) + ':00'
From the above code, date is getting extracted correctly but not the time. any help pls?
You can use the Date object and use Date#toLocaleDateString & Date#toLocaleTimeString method to get your time and date
Or even the Date#toLocaleString to get both at the same time !
const sdt = '2022-05-19T13:00:00';
const date = new Date(sdt)
console.log(date.toLocaleString())
console.log(date.toLocaleDateString())
console.log(date.toLocaleTimeString())
Note that you can specify the location to get the date for a current country
date.toLocaleString('en-GB')
use the Date() constructor:
const sdtString = '2022-05-19T13:00:00'; // https://en.wikipedia.org/wiki/ISO_8601
const sdt = new Date(sdtString); // Date Object {}
then to get the respective date / time use:
Also, worth remembering that getMonth() gives the month's index (zero based), not the number.
I always use a moment.js when dealing with date and time . Just pass the datetime string and specify the format of the output you want .
import moment from 'moment'
var sdt = '2022-05-19T13:00:00';
let time = moment(sdt).format("HH:mm:ss")
let date = moment(sdt).format("DD/MM/YYYY")
console.log(time) //01:00:00
console.log(date) //19/05/2022
https://momentjs.com/ checkout this page to learn about more formats