Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

229
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda