String for date and day subtraction javascript

Asked

Viewed 103 times

0

I need to convert a date that comes as string to Date and subtract a day from that date.

I did it this way:

dataConvertida = new Date("2018-07-03")

But when making the conversion, it automatically cashes a day and I need it to pick exactly the date.

  • Put your code, because the way it’s in the question it doesn’t happen...

  • Do you need to receive this date as a string? Because an option would be to use the input type Date, which will already return you a Date value

  • So he considers the Timezone and does not bring the correct date, you can specify the time and the Timezone, so: new Date('2018-07-03T10:15:00')

  • When you use new Date("2018-07-03"), the result corresponds to this date (3 July 2018), at midnight on UTC (or 2018-07-03T00:00:00Z).&#The problem is that this same date in UTC may correspond to a different date and time in other timezones. For example, in São Paulo, this same value corresponds to 2018-07-02T21:00-03:00 (9 the night of the previous day), and many Date methods use the browser Timezone to interpret the value. How to treat the problem will depend on what you are doing with the date

2 answers

1


Strange even how it happens. It must be something time zone related.

Anyway, I’d have a lot of trouble if instead of "2018-07-03" you put "2018-07-03 00:00"?

That way came out right (at least here)

EDITION 23/07/2019

I know it’s been a while, but anyway. Really the problem is the time zone.

If you use a string with the year, month and day separated with hyphen, the time zone that JS chooses for you is Coordinated Universal Time (UTC), which is the time zone used to calculate the other time zones in the world.

Now if you use bars to separate the year, month and day, the chosen time zone is your local time zone.

I mean, in your case it would have been better to have used "2018/07/03".

Ah, and <input type="date"> generates hyphenated values. Maybe this information will be useful to someone

Source: Exploring Unexpected Behavior With Javascript Date Objects

-1

There is the method stepDown(qnt) which reduces the amount of days of input type=date

<html>
<body>

<input type="date" id="data"> <!-- Pega a data --> 

<button onclick="removerUmDia()">Remover um dia</button> <!-- Botão que ativa a função, esse aqui dependerá de sua aplicação, como sua pergunta não especifica bem a utilização não tenho como ajudar mais que isso -->

<script>
function removerUmDia() {
    document.getElementById("data").stepDown(1); //Pega data e reduz 1 dia
}
</script>

</body>
</html>

Browser other questions tagged

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