Problems with Date () function when converting String to Date

1

I have a problem with the date () function of javascript what I want is to convert from a string to a date but convert the date minus 1 day.

function myFunction() {
var d = new Date('2018-02-28');
var n = d.toString();
document.getElementById("demo").innerHTML = n;
}

what it shows is:

Tue Feb 27 2018 20:00:00 GMT-0400 (Hora estándar oeste, Sudamérica) 

I hope you can help me I need that format, thanks

    
asked by daniela 23.02.2018 в 22:11
source

3 answers

3

as comments Jorge Marquez is necessary to add something else, although something curious is that it is not necessarily the time with minutes and seconds. It also works by simply adding a space after the day, in your case:

var d = new Date('2018-02-28 ');  // Fijese que hay un espacio despues del 28

You can also clarify by placing "00:00", until it works by placing a space and simple colon.

var d = new Date('2018-02-28 :'); 

Greetings.

    
answered by 24.02.2018 / 00:05
source
4

It really is not less a day , but less 4 hours: The Date class when the time is not passed, assumes that the time is 00:00:00 but in the hour use GMT 0000 , so on your machine, which has the time GMT-0400 , appears with 4 hours less.

My advice is to use the moment.js library to simplify, but another solution is to add the time: '2018-02-28 00:00:00'

    
answered by 23.02.2018 в 22:31
2

The reason why the date comes out is because you need to put the whole date with hours minutes and seconds to convert it; like this: 2018-02-28 00:00:00

then your code would be like this

function myFunction() {
  var d = new Date('2018-02-28 00:00:00');
  var n = d.toString();
  document.getElementById("demo").innerHTML = n;
}

greetings

    
answered by 23.02.2018 в 22:26