JS setHours on date is not working correctly - javascript

I have the following code to increment the hours in a date:
let timerExpireDate = new Date(countdownStartDate);
console.log(`original date is ${timerExpireDate}`);
console.log(`add on ${countdownHours} hours`);
timerExpireDate.setHours(timerExpireDate.getHours() + countdownHours);
console.log(`New date is ${timerExpireDate}`);
However it also seems to be incrementing the days by 6, here is the console log:
original date is Sun Jul 19 2020 16:36:39 GMT+0800 (Taipei Standard Time)
add on 2 hours
New date is Sat Jul 25 2020 18:36:39 GMT+0800 (Taipei Standard Time)
What am I doing wrong here?

It is likely that countdownHours is of type string instead of number, so timerExpireDate.getHours() + countdownHours is '162' (6 days later) instead of 18.
The fix is to cast countdownHours to number first, like countdownHours = +countdownHours.

Related

How do I add one day or 12 hours to date in format of Thu Mar 03 2022 12:00:00 GMT in JavaScript [duplicate]

This question already has answers here:
Add one day to date in javascript
(11 answers)
Closed last year.
I want to add one day or 12 hours to a date in the format of
Thu Mar 03 2022 12:00:00 GMT
I have tried:
new Date(value.startDate + 1);
but it does nothing.
Please help me out, I am new to JavaScript.
If you want to add something to your timestamp, this will do the trick no matter what you want to add.
const timestamp = new Date("Thu Mar 03 2022 12:00:00 GMT")
console.log(timestamp.toString())
// because getTime and setTime uses milliseconds:
const millisecondsToBeAdded = 12 * 60 * 60 * 1000
timestamp.setTime(timestamp.getTime() + millisecondsToBeAdded)
console.log(timestamp.toString())
Try this
const date = new Date("Thu Mar 03 2022 12:00:00 GMT");
date.setDate(date.getDate() + 1);

Let value changes out of nowhere

Can someone please explain to me, why start and end variables print to console different values for these loggers?
I get printed out:
start1 = Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time)
end1 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
start2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
end2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
I want to add, that the code I presented is in some method of course, and the names start and end don't interfere with other variable names.
let start = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.start_time_hour,
eventFromUi.start_time_minute
);
console.log("start1 = " + start);
let end = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.end_time_hour,
eventFromUi.end_time_minute
);
console.log("end1 = " + end);
console.log("start2 = " + start);
console.log("end2 = " + end);
EDIT:
The getDateTime() method returns object of TypeScript ootb type Date.
I used Chrome debugger to look into this, and I see that when I first execute the getDateTime() method, I get value Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time) returned and assigned to let start.
Then the method getDateTime() is executed again and retuns value Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time), and this value gets assigned to both start and end variables.
How does this happen?
EDIT2:
Function getDateTime:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
console.log(date);
console.log(hour);
console.log(minute);
date.setHours(hour);
date.setMinutes(minute);
return date;
}
This is happening because you're dealing with object references.
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
// date is now a copy of the *reference* to the same object that
// dateWithoutTime is a reference to. In other words: it is pointing
// to the same object in memory
date.setHours(hour);
date.setMinutes(minute);
// since date is pointing to the same object as dateWithoutTime, this is
// modifying both date and dateWithoutTime
return date;
}
This also means that in your code, eventFromUi.start_date, start and end are all references pointing to the same Date object.
To solve your problem, make sure you create a clone of dateWithoutTime when it is passed into your function:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = new Date(dateWithoutTime);
// date is now a reference to a *new Date object* with the same
// date/time/etc. values as dateWithoutTime
date.setHours(hour);
date.setMinutes(minute);
// since date now points to a new object, this is only modifying date
// while leaving dateWithoutTime alone and unchanged
return date;
}

Function returns incorrect month depending on order of statements

Does anyone have any thoughts on why this might have happened? Today, I found that a date conversion function I wrote started returning the wrong month. For instance, when attempting to convert "2017-06-02" to "Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)", it actually returned July instead of June. When I re-arranged the order of some of the statements in the function, the correct date was finally returned. This code has been in place for many months, so this spontaneous...maybe due to the current month changing, as today is 5/31/17? This might only be broken when ran on todays date, or end-of-month? (I'm sure there's a better way to convert dates, but here's the code in question anyway):
<!doctype html>
<body onload="testDate()">
<div id="resultbad"></div>
<div id="resultgood"></div>
<script>
function testDate() {
document.getElementById("resultbad").innerHTML = "Bad Result: Converting 2017-06-02 returns: " + badDate("2017-06-02");
//returns: Bad Result: Converting 2017-06-02 returns: Sun Jul 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
document.getElementById("resultgood").innerHTML = "Good Result: Converting 2017-06-02 returns: " + goodDate("2017-06-02");
//returns: Good Result: Converting 2017-06-02 returns: Fri Jun 02 2017 00:00:00 GMT-0600 (Mountain Daylight Time)
}
function badDate(d) {
var td = d.split('-');
var nd = new Date();
//originally ordered: Year, Month then Day
nd.setFullYear(td[0]);
nd.setMonth(td[1] - 1);
nd.setDate(td[2]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
function goodDate(d) {
var td = d.split('-');
var nd = new Date();
//new order: Day, Month then Year
nd.setDate(td[2]);
nd.setMonth(td[1] - 1);
nd.setFullYear(td[0]);
//set time
nd.setHours(0);
nd.setMinutes(0,0,0);
return nd;
}
</script>
</body>
This code overrides the date elements based on today's date. So, if you are running the code on the 31st day of the month, the "bad" version of this code will overwrite the month first, and if that month only has 30 days, it will roll over to the next month.
Basically, after setMonth but before setDate, you are trying to create the date June 31, 2017, which JS will convert for you into July 1, 2017.
Instead, do this as one call:
new Date(td[0], td[1]-1, td[2], 0, 0, 0, 0)
You figured out the problem fairly well - it has to do with today being the 31st of the month.
The issue is that new Date() creates a date object with the fields filled in. You're then changing those fields one by one.
So right now we can think of it as having a pseudo-structure like this, remembering that month is 0-based:
{
year: 2017
month: 4
date: 31
}
when you call setMonth(), you're just changing the month field, so you'd think for June it would set it to
{
year: 2017
month: 5
date: 31
}
but it knows there aren't 31 days in June. The 31st "day" of June would be the 1st of July. So it helps you out and adjusts it to
{
year: 2017
month: 6
date: 1
}
You're then setting the date to the 2nd with setDate():
{
year: 2017
month: 6
date: 2
}
In the function that works, you're setting the date before the month, so you're not having it recompute what the day is in case you've specified a date that is larger than the number of days in the month.

Wrong result when converting a date

I am just a beginner. My original date is: Friday, September 16th 2016, 09:00
And I need to convert it to this format: Fri Sep 16 2016 09:00:00 GMT+0000 (GMT)
But my code shows wrong date: Tue Sep 06 2016 09:00:00 GMT+0100 (BST)
Please see my code here:
var startdate = "Friday, September 16th 2016, 09:00";
var sdate = new Date(startdate.replace(/(\d)+(st|nd|th)/g, '$1'));
alert(new Date(sdate));
Can anybody help me with this issue? The example is here: https://jsfiddle.net/5hzwbbku/3/
By using momentjs I receive the strange results: https://jsfiddle.net/5hzwbbku/13/
Your regex is incorrect. /(\d)+(st|nd|th)/g matches the 16th but the captured group only contains 6. In order to return 16 your regex needs to be /(\d+)(st|nd|th)/g, like so:
var sdate = new Date(startdate.replace(/(\d+)(st|nd|th)/g, '$1'));
If you need the time to be in UTC, you'll have to append a timezone such as +0, +0000, or simply Z (for Zulu time).
var startdate = "Friday, September 16th 2016, 09:00";
startdate = startdate + ' +0000';
var sdate = new Date(startdate.replace(/(\d+)(st|nd|th)/g, '$1'));
alert(new Date(sdate));
On my system that returns Fri Sep 16 2016 11:00:00 GMT+0200 (CEST) which is 09:00 in UTC.
Other regexes that match correctly are /(\d)(st|nd|th)/g (note the complete absence of the +) and the one given by pastine in the comments /(.\d)+(st|nd|th)/g.

javascript date and year

I have the following javascript code:
<script type="text/javascript">
$(function () {
var currentDateTime = new Date();
var oneYear = new Date();
oneYear.setYear(oneYear.getYear() + 1);
alert(currentDateTime + "_" + oneYear);
});
</script>
i would expect the alert to output the current datetime and the datetime of one year from now. However I get this in the alert: "Fri Oct 22 2010 14:17:31 GMT-0400 (Eastern Daylight Time)_Thu Oct 22 0111 14:17:31 GMT-0400 (Eastern Daylight Time)"
Clearly it's not adding "1" to the Year correctly!
Whats going on? How did it become the year 0111???
It is correct. .getYear() returns "actual year − 1900". 2010 − 1900 = 110.
Use .getFullYear() instead. .getYear() has been deprecated for a long time.
Y2K was 10 years ago, but you're still using getYear instead of getFullYear? tsk tsk...
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getFullYear
Instead of .getYear() try .getFullYear()

Categories