JavaScript display date from the day before the current date

1

I have the following script that works fine, but at the turn of the month it does not correctly "mounts" the date, for example today, it is showing date 20181000

var today = new Date();
var dd = today.getDate()-1;

var mm = today.getMonth()+1; 
var yyyy = today.getFullYear();
if(dd<10) 
{
    dd='0'+dd;
} 

if(mm<10) 
{
    mm='0'+mm;
} 
var data_ok = today = yyyy+''+mm+''+dd;


var filename = 'ldrel_'+data_ok+'.txt'
    
asked by anonymous 01.10.2018 / 13:47

2 answers

2

var hoje = new Date();

var ontem = new Date(hoje.getTime());
ontem.setDate(hoje.getDate() - 1);

var dd = ontem.getDate();
var mm = ontem.getMonth()+1; 
var yyyy = ontem.getFullYear();

if(dd<10) 
{
dd='0'+dd;
}

if(mm<10) 
{
mm='0'+mm;
} 

var data_ok = yyyy+''+mm+''+dd;

var filename = 'LDREL_'+data_ok+'.txt'

console.log(filename);

The task of the new Date() statement is to create a location in memory for all the data a date needs to store. What is missing from this task is the data - that date and time are placed in that memory location. This is where the parameters come in.

If you leave the parameters empty, JavaScript assumes you want the current date and time for this new date object.

To create a date object for a specified date and time, you have five ways to send values as a parameter to the constructor function new Date ():

  • new Date ("month dd, yyyy hh: mm: ss")
  • new Date ("month dd, yyyy")
  • new Date ("aa, month, dd, hh, mm, ss")
  • new Date ("aa, month, dd")
  • new Date (milliseconds)
  • Most methods of a date object serve to read parts of the date and time information and to change the date and time stored in the object. These two categories of methods are easily identifiable since they begin with the keyword get or set

    objDate.getTime() - milliseconds since 1/1/70 00:00:00 GMT

    objDate.setDate(val) - day within month (1-31)

    objDate.getDate() - date within month

    Date

        
    01.10.2018 / 13:56
    2

    It has a much simpler way of doing this using setTime() . This command arranges the hours of the date object of your choice, accepting parameters from -1 to 24. From 0 to 23, it arranges hours correctly, however, with 24 it goes to the next day, and -1 for the last the previous day. That is.

    var hoje = new Date();
    var ontem = new Date().setHours(-1);
    ontem = new Date(ontem) // o comando setHours devolve a data em milisegundos
    
    var dataformatada = ontem.toLocaleDateString('pt-BR'); // '30/09/2018'
    dataformatada = dataformatada.split('/').reverse().join('') // '20180930'
    var filename = 'LDREL_'+dataformatada+'.txt'
    
    console.log(filename); // LDREL_20180930.txt
    
        
    01.10.2018 / 14:16