Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

226
Views
Extract date and time from datetime string in javascript

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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')
about 4 years ago · Juan Pablo Isaza Report

0

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:

  • Date.prototype.toLocaleTimeString()
  • Date.prototype.toLocaleDateString()

Also, worth remembering that getMonth() gives the month's index (zero based), not the number.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!