1

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?

2
  • Can you the desire result you want ? Commented May 31, 2022 at 15:01
  • You must first convert string into datetime format, using var sdt = new Date('2022-05-19T13:00:00'); Commented May 31, 2022 at 15:04

3 Answers 3

3

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Can you imagine loading js code of above 50kB just for this? See other answers, just "few" bytes more then OP question.
@nelek Well said , I think if the size is an issue probably using js Date is a good option , If its a big project where you work a lot with time and date , moment.js is the best option yet.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.