Format date from the SQL SERVER Database

0

The date that comes from SQL SERVER comes in the following format: 20181212. I tried formatting, but it only works if it comes in the 2018-12-12 format.

I put this date inside a table by the API I pull where the data is (date comes from the API).

function Progress() {

        fetch('http://API_AQUI', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'L2_PRODUTO=${id}'
        }).then(response => response.json().then(data => ({
            data: data,
            status: response.status
        })
        ).then(res => {
            res.data.map(element => {
                $('.progresso-1').append('${element.DATAUM}');
                 $('.progresso-2').append('${element.DATADOIS}');
            }

Then on the front I put:

<tr>
    <td class="td-b">Data Um</td>
    <td class="progresso-1"></td>
</tr>

<tr>
    <td class="td-b">Data Dois</td>
    <td class="progresso-2"></td>
</tr>

It only comes in the format that it gives in the SQL SERVER database: 20181212.

I have this ready form:

                    function formatarData(str){
                    return [str.slice(0, 4), str.slice(4, 6), str.slice(-2)].join('/'); // para formato yyyy-mm-dd
                    // ou para retornar um objeto Date
                    return new Date(str.slice(0, 4), Number(str.slice(4, 6)) + 1, str.slice(-2));

                  }
                  function formatDate(str)
                  {
                      return str.split('/').reverse().join('/');
                  }  

But it's coming 2018/12/12

    
asked by anonymous 16.03.2018 / 13:37

2 answers

0

You can break this to method substr , which takes part of a string using a parameter that tells where to start and another parameter that says how many characters pick up from the initial (if the amount is not given, will get all from the index informed):

function formatDate( date ){
    if( typeof date === "number" ) date = date.toString();

    //Posição 0, 4 digitos = ano
    //Posição 4, 2 digitos = mes
    //Posição 6, 2 digitos = dia
    return '${date.substr( 6 )}-${date.substr( 4, 2 )}-${date.substr( 0, 4 )}';
}

It will look like this:

$( '.progresso-1' ).append( '${formatDate(element.DATAUM)}' );
$( '.progresso-2' ).append( '${formatDate(element.DATADOIS)}' );
    
16.03.2018 / 14:29
0

I still can not comment. Is the date going to the database inserted or is it by default? Have you tried using php

$date = date('d-m-Y', strtotime( $row['date'] ))

This is an example if you are fetching the date from a database field

But you can always use a SQL code for conversion

CONVERT(data_type(length), expression, style)

Take a look at this link

CONVERT SQL

    
16.03.2018 / 14:27