How to remove hours from a Datetime string

Asked

Viewed 381 times

0

I’m pulling a datetime record from my database and I’m formatting it to the traditional Brazilian format, however, I can’t remove the hours after the last value, always repeats the time. This is my job;


const formatarData = (data) =>{
    var arrayData = data.split('-');
    var dataCorreta = `${arrayData[2]}/${arrayData[1]}/${arrayData[0]}`;
    return dataCorreta;
}

Incoming, the result that comes out in formatting is this:

Função para Formatação

3 answers

0

function dataFormatada(dataBanco){
    let data = new Date(dataBanco),
        dia  = data.getDate().toString(),
        diaF = (dia.length == 1) ? '0'+dia : dia,
        mes  = (data.getMonth()+1).toString(), //+1 pois no getMonth Janeiro começa com zero.
        mesF = (mes.length == 1) ? '0'+mes : mes,
        anoF = data.getFullYear();
    
    // return diaF+"/"+mesF+"/"+anoF;

    console.log(diaF+"/"+mesF+"/"+anoF);
}

/* ###### data vindo do banco exemplo com PHP
    dataBanco="<?php echo $dataBanco ?>";
########################################### */

dataBanco="2020-07-06 15:00:00";

//chamada da função
dataFormatada(dataBanco);

The task of instruction new Date( ) is to create a memory location for all the data that a date needs to store.

console.log(new Date("2020-07-06 15:00:00"));

The method getDate() returns the day of the month

The method toString() converts a Date object into a string

let data = new Date("2020-07-06 15:00:00")

console.log(data.getDate().toString());

getMonth() - month in year (January = 0)

getFullYear() - returns the year of the specified date according to local time

With this data you build your date the way you want it

(diaF+"/"+mesF+"/"+anoF)

(anoF+"/"+mesF+"/"+diaF)

0


Note that you used the Split function by specifying the delimiter "-" in the String "2020-07-06 15:00:00".

This way you get 3 strings:

arrayData[0] = "2020"
arrayData[1] = "07"
arrayData[2] = "06 15:00:00"

It is interesting, in this case that first you use the function Split with the delimiter " (space character) to initially separate time from date. And in a second stage use again the split function to separate day, month and year.

Example:

var arrayDataHora = date.split(" ");
var arrayData = arrayDataHora[0].split("-");

0

A possible solution is to use the class Date:

const formatarData = (data) =>{
    let d = new Date(data);
    // Month retorna entre 0 e 11, por isso a adição +1
    return `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()}`
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.