Date difference larger than intended - javascript

I am learning to use Date object in Javascript. Tried to calculate difference between now and some set date, but it returns a much larger value than inteded. The codepen is here, I can't seem to figure what I did wrong... Help?
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
var now = new Date(); //Now, whenever this code runs
var diff = Math.round((setdate.getTime() - now.getTime())/1000); //Difference in seconds
function NiceTimer(delta) { //Decompose the difference in seconds into date units.
this.days = Math.floor(delta/ 86400);
delta -= this.days*86400; //Subtract the value once it has been "extracted".
this.hours = Math.floor(delta/ 3600);
delta -= this.hours*3600;
this.minutes = Math.floor(delta/ 60);
delta -= this.minutes*60;
this.seconds = delta;
this.printString = function() {
return "The event starts in "+this.days+" days, "+this.hours+" hours, "+this.minutes+" minutes and "+this.seconds+" seconds"; //Output a readable countdown string
}
}
var timer = new NiceTimer(diff);
var el = document.getElementById("timer");
el.innerHTML = timer.printString();

var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
Change the four to a three, months start at index zero.
var setdate = new Date(2014, 3, 27, 14,30);
Date # MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.

Related

How to calculate milliseconds since beginning of the day?

I've specified a specific time on a certain day. Now I wish to calculate the milliseconds from the beginning of that specific day to the set time of that day? I was hoping to do that with below code, but instead it shows nothing? What am I doing wrong?
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01").getTime();
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
I specify the countDownDate. Then I mark the beginning of that countDownDate into the variable countDownStart. Next I calculate the time passed since 00:00 of January 10 to 00:01 of January 10 by subtracting countDownStart from countDownDate. But no result is shown...
Your code has only one issue, and that is that you've assigned the result of .getTime() to countDownDate, which will be a number.
That's why JavaScript cannot call getFullYear, or any other function on that number, because those will be invalid calls.
To correct that, just remove the .getTime(), and it will work fine.
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
<div id="result">
<div>
Your logic is fine here. The only issue is this line here:
var countDownDate = new Date("January 10, 2018 00:01").getTime();
Since you used .getTime() the variable countDownDate is no longer a date. As such in the following statementcountDownDate.getFullYear() and forward isn't going to work. Simply remove .getTime() and it will work as expected:
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
console.log(countDownTime)

hours difference between two years (With leap year) in javascript

How can i get the hours difference between two years (With leap year) in javascript
I have two year 2015 and 2014
var year1="2015";
var year="2016";
I want to get the total hours different between those above years by one line code(with leap year and without leap year)!.
I have tried this below code
// get hours from one year
var date = new Date;
var Hours= date.getFullYear().getHours();
// get hours between two years
var Hours= (date.getFullYear()-dat2.getFullYear()).getHours()
But It's something wrong for me.
You could use a function similar to this:
function getHoursBetweenYears(startYear, endYear) {
var startDate = new Date(startYear, 0, 1),
endDate = new Date(endYear, 0 ,1);
return (+endDate - +startDate) / 3600000;
}
Usage like this:
getHoursBetweenYears(2012, 2013) // 8784
Date object is your saver.
Get time differance. then multiply with min, s, ms.
Gives you time diff total hour between years.
var year=2015,
year1=2016,
timeDiff =(new Date("01/01/"+year1)-new Date("01/01/"+year))/(1000*60*60);
The leap year should be specified by year and also month. So
March d + 59 Add 1 if leap year
….up to
December d + 334 Add 1 if leap year
You can try something like this.
hours = ((new Date()).setFullYear( 2016 ) - (new Date()).setFullYear( 2015 ))/(1000*3600);
View demo jsFiddle
var start = new Date(2015, 0, 0);
var end = new Date(2016, 0, 0);
var diff = end - start;
var oneDay = 1000 * 60 * 60;
var day = Math.floor(diff / oneDay);
alert("Hours: " + day);
Answer
Hours: 8760
Calculate the diffference in milliseconds from two dates (including the first day of the start year and the last day of the end year) and divide the result by 3600000 (1000 * 60 * 60 = milliseconds in one hour):
// difference in hours for two whole years (2015-2016)
var hourdiff = (new Date('2017/01/01') - new Date('2014/12/31'))/(1000*60*60);
You can create a Date extension to calculate hours in a certain year:
Date.prototype.hoursInYear = function() {
return ( (new Date(this.getFullYear()+1, 0, 1)) -
(new Date(this.getFullYear()-1, 11, 31)) ) / 3600000; }
// usage
new Date(1997, 0, 1).hoursInYear(); // => 8784
new Date(2008, 0, 1).hoursInYear(); // => 8808 (leap year)
Or even (the number of hours in a (leap)year is constant)
Date.prototype.hoursInYear = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1
? 8808 : 8784;
}
And finally, using the Date extension, this could be a method to calculate the number of hours in [n years] starting with [startyear]:
function calcHours(startyear, numyears) {
return isNaN(new Date(startyear, 0, 1))
? null // invalid year value
: Array.apply(null, {0: startyear, length: numyears})
.map(function(v, i) {return v == this ? v : this + 1;}, startyear)
.reduce( function(a, b) {
return a + new Date(b, 0, 1)
.hoursInYear();}, 0);
}
// usage
calcHours(2000, 2); //=> 17592 (2000 is leap year)
calcHours(2001, 2); //=> 17568
Get the seconds of both years. setFullYear gives you the unix timestamp in millis. Divide by 1000 and you have seconds. Get the difference between the two years and divide this through 3600 (seconds per hour). Then you have your difference in hours.
function getDiffHours (year1, year2) {
var d1 = new Date().setFullYear(year1) / 1000;
var d2 = new Date().setFullYear(year2) / 1000;
var diff = Math.abs(d2 - d1);
return Math.floor(diff / 3600);
}

Javascript - Date difference is incorrect

I need to get the difference in seconds between two dates and times.
I have this script:
var date1 = new Date(2013,10,02,12,00,00);
var date2 = new Date(2013,10,02,12,01,00);
var diff = date2 - date1;
diff = diff / 1000;
document.write(diff);
Which returns the value of 60, 60 seconds difference, good.
However, when I cross over a month with 30 days, it doesn't calculate correctly.
var date1 = new Date(2013,9,30,12,00,00);
var date2 = new Date(2013,10,02,12,00,00);
var diff = date2 - date1;
diff = diff / 1000;
document.write(diff);
The result returned is 259200, which is 3 days. The difference between September 30 and October 2 is only 2 days, 172800, because there are only 30 days in the month. Why does Javascript seem to think there are 31 days in September?
The month numbers start with 0, not 1. So 9 is October and 10 is November.

Countdown in Javascript

I would like to put on our company intranet page the number of days until the next payday, however - the payday dates aren't every 4 weeks etc. they will be similar to this:
1st January 2011
15th February 2011
12th March 2011
20th April 2011
...
Is it possible to have a javascript countdown clock that has the above dates listed, so once one date has passed it would then start counting down until the next calendar date?
I can find plenty of examples of scripts that countdown until a specific date but none that start counting down to the second date once the first has passed.
Thanks,
Dan
Put the dates in an array. Be careful, in Javascript the months are zero-based so ranging from 0 to 11. Iterate the array and when the date is bigger then today display the days in between:
var calcPayDate = function () {
var payDates = [];
payDates.push(new Date(2011, 0, 1));
payDates.push(new Date(2011, 1, 15));
payDates.push(new Date(2011, 2, 12));
payDates.push(new Date(2011, 3, 20));
var today = new Date();
for (var i = 0; i < payDates.length; i++) {
if (payDates[i] > today) {
document.getElementById('countdownDiv').innerHTML = calcDays(payDates[i], today);
break;
}
}
}
var calcDays = function(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY)
}
The calcDays function is an function found on this site
The days are put in a div which is called 'countdownDiv'.
Search the web for "JavaScript tutorial".
Meanwhile, here's some code to get you started:
var dates = [
new Date(2011, 0, 1), // note that format is year, month-1, day
new Date(2011, 1, 15), // don't ask me why
new Date(2011, 2, 12),
new Date(2011, 3, 20)
];
var now = new Date();
for (var i in dates) { // this is a foreach loop
if (now < dates[i]) {
document.write(Math.ceil((dates[i] - now) / 86400000));
break;
}
}

JavaScript - get the first day of the week from current date

I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas?
Using the getDay method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).
You can then subtract that number of days plus one, for example:
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
Not sure how it compares for performance, but this works.
var today = new Date();
var day = today.getDay() || 7; // Get current day number, converting Sun. to 7
if( day !== 1 ) // Only manipulate the date if it isn't Mon.
today.setHours(-24 * (day - 1)); // Set the hours to day number minus 1
// multiplied by negative 24
alert(today); // will be Monday
Or as a function:
# modifies _date_
function setToMonday( date ) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
setToMonday(new Date());
CMS's answer is correct but assumes that Monday is the first day of the week.
Chandler Zwolle's answer is correct but fiddles with the Date prototype.
Other answers that add/subtract hours/minutes/seconds/milliseconds are wrong because not all days have 24 hours.
The function below is correct and takes a date as first parameter and the desired first day of the week as second parameter (0 for Sunday, 1 for Monday, etc.). Note: the hour, minutes and seconds are set to 0 to have the beginning of the day.
function firstDayOfWeek(dateObject, firstDayOfWeekIndex) {
const dayOfWeek = dateObject.getDay(),
firstDayOfWeek = new Date(dateObject),
diff = dayOfWeek >= firstDayOfWeekIndex ?
dayOfWeek - firstDayOfWeekIndex :
6 - dayOfWeek
firstDayOfWeek.setDate(dateObject.getDate() - diff)
firstDayOfWeek.setHours(0,0,0,0)
return firstDayOfWeek
}
// August 18th was a Saturday
let lastMonday = firstDayOfWeek(new Date('August 18, 2018 03:24:00'), 1)
// outputs something like "Mon Aug 13 2018 00:00:00 GMT+0200"
// (may vary according to your time zone)
document.write(lastMonday)
First / Last Day of The Week
To get the upcoming first day of the week, you can use something like so:
function getUpcomingSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - currentDay + 7);
return new Date(newDate);
}
console.log(getUpcomingSunday());
Or to get the latest first day:
function getLastSunday() {
const date = new Date();
const today = date.getDate();
const currentDay = date.getDay();
const newDate = date.setDate(today - (currentDay || 7));
return new Date(newDate);
}
console.log(getLastSunday());
* Depending on your time zone, the beginning of the week doesn't has to start on Sunday, it can start on Friday, Saturday, Monday or any other day your machine is set to. Those methods will account for that.
* You can also format it using toISOString method like so: getLastSunday().toISOString()
Check out Date.js
Date.today().previous().monday()
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
I'm using this
function get_next_week_start() {
var now = new Date();
var next_week_start = new Date(now.getFullYear(), now.getMonth(), now.getDate()+(8 - now.getDay()));
return next_week_start;
}
Returns Monday 00am to Monday 00am.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay() + 1)
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
Good evening,
I prefer to just have a simple extension method:
Date.prototype.startOfWeek = function (pStartOfWeek) {
var mDifference = this.getDay() - pStartOfWeek;
if (mDifference < 0) {
mDifference += 7;
}
return new Date(this.addDays(mDifference * -1));
}
You'll notice this actually utilizes another extension method that I use:
Date.prototype.addDays = function (pDays) {
var mDate = new Date(this.valueOf());
mDate.setDate(mDate.getDate() + pDays);
return mDate;
};
Now, if your weeks start on Sunday, pass in a "0" for the pStartOfWeek parameter, like so:
var mThisSunday = new Date().startOfWeek(0);
Similarly, if your weeks start on Monday, pass in a "1" for the pStartOfWeek parameter:
var mThisMonday = new Date().startOfWeek(1);
Regards,
a more generalized version of this... this will give you any day in the current week based on what day you specify.
//returns the relative day in the week 0 = Sunday, 1 = Monday ... 6 = Saturday
function getRelativeDayInWeek(d,dy) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:dy); // adjust when day is sunday
return new Date(d.setDate(diff));
}
var monday = getRelativeDayInWeek(new Date(),1);
var friday = getRelativeDayInWeek(new Date(),5);
console.log(monday);
console.log(friday);
Simple solution for getting the first day of the week.
With this solution, it is possible to set an arbitrary start of week (e.g. Sunday = 0, Monday = 1, Tuesday = 2, etc.).
function getBeginOfWeek(date = new Date(), startOfWeek = 1) {
const result = new Date(date);
while (result.getDay() !== startOfWeek) {
result.setDate(result.getDate() - 1);
}
return result;
}
The solution correctly wraps on months (due to Date.setDate() being used)
For startOfWeek, the same constant numbers as in Date.getDay() can be used
setDate() has issues with month boundaries that are noted in comments above. A clean workaround is to find the date difference using epoch timestamps rather than the (surprisingly counterintuitive) methods on the Date object. I.e.
function getPreviousMonday(fromDate) {
var dayMillisecs = 24 * 60 * 60 * 1000;
// Get Date object truncated to date.
var d = new Date(new Date(fromDate || Date()).toISOString().slice(0, 10));
// If today is Sunday (day 0) subtract an extra 7 days.
var dayDiff = d.getDay() === 0 ? 7 : 0;
// Get date diff in millisecs to avoid setDate() bugs with month boundaries.
var mondayMillisecs = d.getTime() - (d.getDay() + dayDiff) * dayMillisecs;
// Return date as YYYY-MM-DD string.
return new Date(mondayMillisecs).toISOString().slice(0, 10);
}
Here is my solution:
function getWeekDates(){
var day_milliseconds = 24*60*60*1000;
var dates = [];
var current_date = new Date();
var monday = new Date(current_date.getTime()-(current_date.getDay()-1)*day_milliseconds);
var sunday = new Date(monday.getTime()+6*day_milliseconds);
dates.push(monday);
for(var i = 1; i < 6; i++){
dates.push(new Date(monday.getTime()+i*day_milliseconds));
}
dates.push(sunday);
return dates;
}
Now you can pick date by returned array index.
An example of the mathematically only calculation, without any Date functions.
const date = new Date();
const ts = +date;
const mondayTS = ts - ts % (60 * 60 * 24 * (7-4) * 1000);
const monday = new Date(mondayTS);
console.log(monday.toISOString(), 'Day:', monday.getDay());
const formatTS = v => new Date(v).toISOString();
const adjust = (v, d = 1) => v - v % (d * 1000);
const d = new Date('2020-04-22T21:48:17.468Z');
const ts = +d; // 1587592097468
const test = v => console.log(formatTS(adjust(ts, v)));
test(); // 2020-04-22T21:48:17.000Z
test(60); // 2020-04-22T21:48:00.000Z
test(60 * 60); // 2020-04-22T21:00:00.000Z
test(60 * 60 * 24); // 2020-04-22T00:00:00.000Z
test(60 * 60 * 24 * (7-4)); // 2020-04-20T00:00:00.000Z, monday
// So, what does `(7-4)` mean?
// 7 - days number in the week
// 4 - shifting for the weekday number of the first second of the 1970 year, the first time stamp second.
// new Date(0) ---> 1970-01-01T00:00:00.000Z
// new Date(0).getDay() ---> 4
It is important to discern between local time and UTC. I wanted to find the start of the week in UTC, so I used the following function.
function start_of_week_utc(date, start_day = 1) {
// Returns the start of the week containing a 'date'. Monday 00:00 UTC is
// considered to be the boundary between adjacent weeks, unless 'start_day' is
// specified. A Date object is returned.
date = new Date(date);
const day_of_month = date.getUTCDate();
const day_of_week = date.getUTCDay();
const difference_in_days = (
day_of_week >= start_day
? day_of_week - start_day
: day_of_week - start_day + 7
);
date.setUTCDate(day_of_month - difference_in_days);
date.setUTCHours(0);
date.setUTCMinutes(0);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date;
}
To find the start of the week in a given timezone, first add the timezone offset to the input date and then subtract it from the output date.
const local_start_of_week = new Date(
start_of_week_utc(
date.getTime() + timezone_offset_ms
).getTime() - timezone_offset_ms
);
I use this:
let current_date = new Date();
let days_to_monday = 1 - current_date.getDay();
monday_date = current_date.addDays(days_to_monday);
// https://stackoverflow.com/a/563442/6533037
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
It works fine.
Accepted answer won't work for anyone who runs the code in UTC-XX:XX timezone.
Here is code which will work regardless of timezone for date only. This won't work if you provide time too. Only provide date or parse date and provide it as input. I have mentioned different test cases at start of the code.
function getDateForTheMonday(dateString) {
var orignalDate = new Date(dateString)
var modifiedDate = new Date(dateString)
var day = modifiedDate.getDay()
diff = modifiedDate.getDate() - day + (day == 0 ? -6:1);// adjust when day is sunday
modifiedDate.setDate(diff)
var diffInDate = orignalDate.getDate() - modifiedDate.getDate()
if(diffInDate == 6) {
diff = diff + 7
modifiedDate.setDate(diff)
}
console.log("Given Date : " + orignalDate.toUTCString())
console.log("Modified date for Monday : " + modifiedDate)
}
getDateForTheMonday("2022-08-01") // Jul month with 31 Days
getDateForTheMonday("2022-07-01") // June month with 30 days
getDateForTheMonday("2022-03-01") // Non leap year February
getDateForTheMonday("2020-03-01") // Leap year February
getDateForTheMonday("2022-01-01") // First day of the year
getDateForTheMonday("2021-12-31") // Last day of the year
Extending answer from #Christian C. Salvadó and information from #Ayyash (object is mutable) and #Awi and #Louis Ameline (set hours to 00:00:00)
The function can be like this
function getMonday(d) {
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
d.setDate(diff);
d.setHours(0,0,0,0); // set hours to 00:00:00
return d; // object is mutable no need to recreate object
}
getMonday(new Date())
Check out: moment.js
Example:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Bonus: works with node.js too

Categories

Resources