I need to add 4 hours to my moment js date. So for that i am using
/* this timestamp is this date 27-03-2045 00:00 */
const someday = moment(2374178400000);
const addedFourHours = someday.add(4, 'hours');
on 27 March the DST is already passed and i get exactly 4 hours added and the end date in addedFoursHours
is Mon Mar 27 2045 04:00:00 GMT 0200
.
But when i try date when DST is happening for example 26 March on midnight
/* this timestamp is this date 26-03-2045 00:00 */
const someday = moment(2374095600000);
const addedFourHours = someday.add(4, 'hours');
then i get Sun Mar 26 2045 05:00:00 GMT 0200
. In previous case i got 04:00 time when i added 4 hours after midnight. Why in DST time i get 05:00 time ?
How can i solve this ?
CodePudding user response:
What you want is then actually not adding 4 hours, but finding the next time where the hours are a multiple of 4.
So, remove all suggestion from your code that you are adding four hours (cf. your variable name).
You can do this:
const someday = moment(2374095600000);
console.log(someday.toString());
const hours = someday.hours();
someday.hours(hours 4 - (hours % 4)); // Find next time that is multiple of 4.
console.log(someday.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
CodePudding user response:
You want to add 3, 4 or 5 hours depending on the date, but you want to set specific values for the hours. Read the hour value, add 4 and set the value:
const today = moment(2374178400000);
const four = moment(today).hours(today.hour() 4);
const eight = moment(four).hours(four.hour() 4);
const twelve = moment(eight).hours(eight.hour() 4);
const sixteen = moment(twelve).hours(twelve.hour() 4);
const twenty = moment(sixteen).hours(sixteen.hour() 4);
const tomorrow = moment(twenty).hours(twenty.hour() 4);
console.log(today);
console.log(four);
console.log(eight);
console.log(twelve);
console.log(sixteen);
console.log(twenty);
console.log(tomorrow);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>