Multiple day(s) left javascript timer for multiple time zones - javascript

What I am trying to accomplish is multiple countdowns with different expiration dates. I have a code snippet from Codepen, I used as a starting point that works for just one countdown. I am also hoping that no matter whether the viewer is in California, or Georgia the expiration will know what the time zone is. I added the suggested getTimezoneOffset() to deal with different time zones. Which causes the countdown to multiply the days remaining to an absurd number that is 50 years in the future. When I remove that, it is fine. So I have not figured out how to implement that suggestion correctly. Through much trial and error I did successfully create a duplicate countdown with a different expiration date. The only thing I don't understand still is how to implement getTimezoneOffset() so that it does not display 17,893 and 17,883 days (50 years worth of days). I am a trial and error javascript modifier. I try stuff until something is no longer broken.
var countDownDate = new Date("DEC 27, 2018").getTime();
var countDownDate2 = new Date("DEC 17, 2018").getTime();
// COPY FEED
var data = {
// OFFER 1
one: "Offer One",
two: "Free Product",
three: "Today Only",
// OFFER 2
four: "Offer Two",
five: "Free Pickup",
six: "<span id='daysLeft'></span> <span id='plural'></span>",
seven: "Expires: Dec. 27, 2018",
// OFFER 3
eight: "Offer Three",
nine: "<span id='daysLeft2'></span> <span id='plural2'></span>",
ten: "Expires: Dec. 17, 2018",
};
// LOOP THROUGH KEYS TO GET ALL ELEMENT IDs & CREATE VARIABLES
function bannerFunc() {
for (key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
var key = document.getElementById('" + key + "');
}
}
// ASSIGN OBJECT VALUES TO VARIABLES
one.innerHTML = data.one;
two.innerHTML = data.two;
three.innerHTML = data.three;
four.innerHTML = data.four;
five.innerHTML = data.five;
six.innerHTML = data.six;
seven.innerHTML = data.seven;
eight.innerHTML = data.eight;
nine.innerHTML = data.nine;
ten.innerHTML = data.ten;
// DATE CODE
var x = setInterval(function() {
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural');
plural.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural.innerHTML = 'Expired';
}
var now = new Date().getTimezoneOffset(),
amountLeft = countDownDate2 - now,
days = Math.floor(amountLeft / (1000 * 60 * 60 * 24) + 1),
plural = document.getElementById('plural2');
plural2.innerHTML = days + ' Days Left';
if( days < 2 && days > 0 ){
plural2.innerHTML = days + ' Day Left';
}
if( days <= 0 ){
plural2.innerHTML = 'Expired';
}
}, 1000);
}
bannerFunc();

Use the getTimeZoneOffset for your date calculations. Then define all your dates as UTC dates. (https://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp).
More about JS Dates

Related

Javascript: convert number of days to years, months and days

I have days, months and years. I'm doing calculations between them. That means I have to divide 2 years 3 months and 10 days by 1/4. Now i have following code:
const getCurrentDate = moment().format("YYYY-MM-DD");
const timeEnd = moment(moment(DefEndDate).format("YYYY-MM-DD"));
const diff = timeEnd.diff(getCurrentDate);
const diffDuration = moment.duration(diff);
const diffCount = moment.duration(diff).asDays();
console.log(diffCount);
console.log("Years:", diffDuration.years());
console.log("Month:", diffDuration.months());
console.log("Days:", diffDuration.days());
const diffCount = moment.duration(diff).asDays(); //Get it as days
const [unserve, setUnserve] = useState(''); //set value to variable
const res = unserve.split('/'); //split 1/4 to 1.4
const x = parseFloat(res[0] + "." + res[1]); //convert it to float
var quotient = Math.floor(diffCount/x); //calculate
console.log(quotient);
//returned 832 / 1.4 = 594 days
Now I need to return the output number (days) to the year, month and day. I can't do that. How do I convert? And another question is, can this way be the optimal solution?
I can't decide whether what you really want to do is divide a date range in to a fixed number of periods with equal days, or to start with a date, add a period in years, months and days to get an end date, then divide that into equal periods.
The following assumes the latter.
I have to divide 2 years 3 months and 10 days by 1/4
The number of days covered by that period varies depending the dates it is to and from, so you have to start with the start and end dates of the range.
In your code:
const getCurrentDate = moment().format("YYYY-MM-DD");
Sets getCurrentDate to a string like 2020-02-11.
const timeEnd = moment(moment(DefEndDate).format("YYYY-MM-DD"));
Creates a moment object from the string value of getCurrentDate and sets timeEnd to another string.
const diff = timeEnd.diff(getCurrentDate);
This attempts to call the diff method of timeEnd, which is a string. Strings don't have a diff method so the expression returns undefined, attempting to call it throws an error something like TypeError: '2020-02-11'.diff is not a function.
The rest of your code seems to be based on a algorithm
If you have a predetermined period in years, months days, etc. you can start with a start date, add the period, then get the number of days difference. Divide that difference by the number of periods you want, then add that sequentially to get the various end dates.
The following example uses moment.js since that's what you appear to be using, however a version without a library is about the same difficulty. It returns an array of dates, starting with the start date so there is one more date than periods.
function getDates(
start = new Date(),
years = 0,
months = 0,
days = 0,
parts = 1) {
// Get start and end as moment objects
let m = moment(start).startOf('day');
let end = moment(m);
end.add({years:years, months:months, days:days});
// Get days difference and number of days to add for each period
let daysDiff = end.diff(m, 'days');
let f = daysDiff / parts;
let dayArray = [m.format('YYYY-MM-DD')];
let i = 0;
while ((f * ++i) <= daysDiff) {
let d = moment(m).add(f * i, 'days')
dayArray.push(d.format('YYYY-MM-DD'));
}
return dayArray;
}
// Get dates for 4 even periods over 2 years, 3 months and
// 10 days from today
console.log(getDates(new Date(), 2, 3, 10, 4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
As the sub–period length is nearly always not an even number of days (in the above case it's about 207.5), I've allowed formatting to effectively truncate the decimal part of a day. You might want to use some other rounding algorithm that more evenly distributes the remainder.
If, on the other hand, you have start and end dates and want an equal number of periods, the following is much simpler (and doesn't use a library):
// Helpers - use UTC do avoid DST issues
function toUTCDate(s) {
let b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2]));
}
function formatUTC(date) {
return date.toISOString().substr(0, 10);
}
/* #param {string} start - date string in format 'YYYY-MM-DD'
** #param {string} end - date string in format 'YYYY-MM-DD'
** #param (numbe} n - number of required periods
** #returns {Array} array of date strings in format 'YYYY-MM-DD'
*/
function periods(start, end, n) {
let s = toUTCDate(start);
let e = toUTCDate(end);
let diff = e - s;
let f = diff / n;
let result = [formatUTC(s)];
// Allow for rounding of decimal f in comparison
while (e - s > n) {
s.setTime(s.getTime() + f);
result.push(formatUTC(s))
}
return result;
}
console.log(periods('2020-02-09','2022-05-19', 4));
The two methods produce slightly different results, you'll need to work out if that matters or not.
Long time ago I used such code to convert from seconds to hours, minutes and seconds:
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - hours * 3600) / 60);
var seconds = Math.round(sec - hours * 3600 - minutes * 60);
Math with days, months and years should be somewhat similar but my rusty brain doesn't want to think about it
UPD
This function seems to do what you need
const daysFmt = days => {
const years = Math.floor(days / 365);
const months = Math.floor((days - years * 365) / 30);
const d = Math.round(days - years * 365 - months * 30);
let res = [];
if (years > 0) {
res.push(years + ' y');
}
if (months > 0) {
res.push(months + ' m');
}
if (d > 0) {
res.push(d + ' d');
}
return res.join(', ');
}
But this solution has one nuance: it assumes that month = 30 days. You might want to add if statement to return '1 m' if input is 31 or just return number of days if it is less than 32. Test results:
daysFmt(31);
"1 m, 1 d"
daysFmt(180);
"6 m"
daysFmt(185);
"6 m, 5 d"
daysFmt(356);
"11 m, 26 d"
daysFmt(365);
"1 y"
daysFmt(420);
"1 y, 1 m, 25 d"
daysFmt(3650);
"10 y"
daysFmt(3685);
"10 y, 1 m, 5 d"

How do I get the number of days for a duration where the number of hours exceeds 24 in google sheets?

I am using google sheets where there is a duration value of 69:41:00 where it's 69 hours, 41 minutes, 0 secs. There doesn't seem to be a function to convert this to days, hours and minutes so I did some searching and some had suggested a custom function. Not sure exactly how it works but made some changes from the original to fit what I needed. The code below:
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Retrieve the hours and minutes
var hrs = duration.getHours();
var days = Math.floor(hrs/24);
var hours = hrs % 24;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
The result should be 2d 21h 44 min but instead I got 0d 21 h 35 min. Am I doing something wrong here?
I was going to add, why don't you just use a custom format of
ʺd\d hh\h mm\mʺ ?
This works fine in Excel but not in GS because it uses a different base for dates so duration like 69:41:00 would be interpreted as 1/1/1900 21:41 and the days are not correct. So you would have to break it down into days (whole numbers) and hours+minutes (fractions of a day) like this
=text(int(A1),ʺ#0\d ʺ)&text(mod(A1,1),ʺHH\h MM\mʺ)
You can make it work in Google Scripts if you want to by adjusting the date - should work OK for durations up to 1 month.
The reason for adding 2 to the date is that a time like 03:21:00 (less than a day) is seen as a date - namely 30th December 1899 ! So I add 2 to it to make it 1st January 1900. However, now the day part of the date is 1 and I want it to be zero. So I have to subtract 1 from the day further down.
This strange behaviour is probably why you're advised to do it the other way and work in milliseconds, but I was just interested to see if there was a way of making the original code work.
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Add 2 days to the date
var date=new Date(duration.setDate(duration.getDate()+2));
Logger.log(date.getDate());
var hours = duration.getHours();
// Take 1 off the day part of the date
var days = date.getDate()-1;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
function(durations){
var timeArr = durations.split(':'); //["69","41","00"]
//your code
}
getHours is a method of object Date.
var t = new Date;
t.getHours();
How do you expect to get more than 24hours from a Date object? It is not the same as what you expect as Duration. Date is for points of time in calendar, so at most you'd get the 23:59:59 of any day. You can get date2 - date1 = milliseconds diff, and work on it, as following;
function FormatDuration(date1, date2) {
var milliseconds = date2 - date1;
var mins = Math.floor((milliseconds / (1000*60)) % 60);
var hours = Math.floor((milliseconds / (1000*60*60)) % 24);
var days = Math.floor(milliseconds / (1000*60*60*24));
var result = days + ' d ' + hours + ' h '+ mins + ' min';
console.log(result);
}
FormatDuration(new Date(2000, 5, 1, 5, 13, 0, 0),
new Date(2000, 5, 2, 15, 31, 0, 0))
You can find more details here

Time difference between 2 datetime moment

SO i have 2 datetime objects .
now = Nov 15 4:00 PM
later = Nov 15 6:00PM
My objective is to get the total hours between (9AM to 5 PM) , given the now and later times.
resulting answer shud be 1 hour. (since im only concerned about time range that falls within 9AM-5PM)
now = Nov 15 6:00 AM
later = Nov 15 8:00 PM
resulting answer should be 8 hours.
is the best way to achieve this using the diff function in moment and stripping the hour out and calculating individual use cases ( when start time less than 9AM/ start time greater than 9AM) . similarly end time (less than 5PM/greater than 5PM) etc?
Also how to tackle this case where,
now = Nov 15 9:00AM
later = Nov 18 2:00PM
resulting answer shud be ,
8(nov 15)+8(nov 16)+8(nov 17)+5(nov 18) = 29hrs
Here's working solution
var now = moment("15 Nov 2016, 9:00:00 am", "DD MMM yyyy, h:mm:ss a").toDate();
var later = moment("18 Nov 2016, 2:00:00 pm", "DD MMM yyyy, h:mm:ss a").toDate();
function getWorkingHours(now, later) {
var hoursToday = 0;
var workingHourStart = 9;
var workingHourEnd = 17;//5pm
var workDuration = workingHourEnd - workingHourStart;
if(workingHourEnd - getHours(now) > 0) {
hoursToday = (workingHourEnd - getHours(now));
hoursToday = (hoursToday > workDuration) ? workDuration : hoursToday;
}
var hoursLater = 0;
if(getHours(later) - workingHourStart > 0) {
hoursLater = (getHours(later) - workingHourStart);
hoursLater = (hoursLater > workDuration) ? workDuration : hoursLater;
}
var actualDiffHours = (later.getTime() - now.getTime()) / (1000 * 60 * 60);
var actualHoursInBetween = actualDiffHours - (24 - getHours(now)) - getHours(later);
var workingHoursInBetween = (actualHoursInBetween / 24) * 8;
return hoursToday + workingHoursInBetween + hoursLater;
}
function getHours(date) {
var hours = date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 3600/1000;
return hours;
}
console.log(getWorkingHours(now, later));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
This should do the job:
const now = moment(new Date(2016, 11, 15, 9, 0, 0));
const then = moment(new Date(2016, 11, 18, 14, 0, 0));
function calDiff(now, then) {
if (now.hour() < 9) {
now.hour(9);
}
if (then.hour() > 17) {
then.hour(17);
}
const total = then.diff(now, 'hours');
const day = Math.floor(total / 24);
return total - (16 * day);
}
console.log(calDiff(now, then));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
Complicated... Function getActiveHours calculates all active slots between start and finish dates, both inclusive, and then removes the missing hours at the beginning of the start date and at the end of the finish date.
var getDateObject = function (date) {
if (date && date.constructor.name == "Array") {
while (date.length < 7) {date.push(0);}
date = new Date(date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
} else if (typeof date == 'string' || typeof date == 'number') {
date = new Date(date);
}
return date;
};
var trimDate = function (date, period) {
var periods = ['second', 'minute', 'hour', 'day'];
period = periods.indexOf(period);
if (typeof date != 'number') {date = getDateObject(date).getTime();}
date = Math.floor(date/1000);
if (period > 0) {date = Math.floor(date/60);}
if (period > 1) {date = Math.floor(date/60);}
if (period > 2) {date = Math.floor(date/24);}
return new Date(date*24*60*60*1000);
};
var getOffset = function (date) {return getDateObject(date).getTimezoneOffset()*60*1000;};
var addOffset = function (date) {
date = getDateObject(date);
return new Date(date.getTime()+getOffset(date));
};
var getActiveHours = function (iniDateTime, endDateTime, startHour, finishHour) {
var hourMs = 60*60*1000; // Define daily active hours 0-24 (decimal 17.5 = 5:30pm):
if (startHour == null) {startHour = 9;}
if (finishHour == null) {finishHour = 17;}
startHour *= hourMs; finishHour *= hourMs;
iniDateTime = getDateObject(iniDateTime).getTime();
endDateTime = getDateObject(endDateTime).getTime();
var iniDayTime = addOffset(trimDate(iniDateTime, 'day')).getTime();
var endDayTime = addOffset(trimDate(endDateTime, 'day')).getTime();
var totalHoursMs = (endDayTime-iniDayTime+24*hourMs)*(finishHour-startHour)/hourMs/24;
var iniHoursNotInMs = iniDateTime-iniDayTime-startHour;
var endHoursNotInMs = endDayTime+finishHour-endDateTime;
return (totalHoursMs-iniHoursNotInMs-endHoursNotInMs)/hourMs;
};
console.log(Math.round(getActiveHours('2016-09-13 11:45:38', '2016-09-15 15:30:25'))); // 20 // Use Math round or floor
I had started writing this awhile back when I first saw the question, but got caught up. My answer is very similar to Khang's, but we went about a certain section of it a little differently.
The basic idea behind the code is that it takes two moment objects. If the start hours are less than nine, we set them to be nine, and if the end hours are greater than 17 (5pm) we set them to be 17.
Next we get the difference between the two objects in days. For each day we know that there are 8 hours the person can get credit for. I then move the date of the start day to the end day, and take the hours between them.
The idea behind this is that if both times are within the same days, there will be 0 days difference. If it is 1, then we will get a total of 8 hours regardless where we start in the day. the only cases I haven't tested are things where the start time is greater than the end time (I'll test it ASAP and make an edit if there's anything I need to change)
Edit
there was indeed a problem if the start time was after the end time (the hours).
This was fixed by adding in one if statement.
$(function() {
function getActiveHours(start, end) {
if (start.hours() < 9) start.hours(9);
if (end.hours() > 17) end.hours(17);
//These two if's should remove most of the issues when we are doing basic work
var days = end.diff(start, 'days');
if (days == 0 && (end.date() - start.date()) == 1) days = 1;
var hours = (days * 8); //gets the hours
start.date(end.date());
var diff = end.diff(start, 'hours');
return hours + diff;
}
var start = moment([2016, 10, 15, 9, 0, 0]);
var end = moment([2016, 10, 18, 14, 0, 0]);
$('#results').html('Total hours worked from ' + start.format('MM-DD-YYYY # hh:mm:ss') + ' to ' + end.format('MM-DD-YYYY # hh:mm:ss') + ' is ' + getActiveHours(start, end))
});
<div id="results"></div>

Time Difference between days [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between dates in JavaScript
I've found myself at a javascript brick wall.
I would like to find the difference (in hours and minutes) between two times on two different days.
I can produce the hours, minutes and day of the week for each but cannot work out how to implement a function that will check how long there is until the next time.
Example:
If it's 16:00 on Friday and the next time is Monday at 13:00 the output would be 69 hours and 0 minutes.
Anyone got any ideas on how best to implement this?
N.B. I'm heavily using Google Closure.
var yourTimeStart = 'Friday 16:00'; //Your input
var yourTimeStop = 'Monday 13:00'; //Your input
var days = Array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
var differenceDays = days.indexOf(yourTimeStop.split(" ")[0]) - days.indexOf(yourTimeStart.split(" ")[0]);
if (days.indexOf(yourTimeStart.split(" ")[0]) > days.indexOf(yourTimeStop.split(" ")[0])) differenceDays = differenceDays + 7;
var timeStart = yourTimeStart.split(" ")[1];
var timeStop = yourTimeStop.split(" ")[1];
var differenceHours = timeStop.split(":")[0] - timeStart.split(":")[0];
var differenceMins = timeStop.split(":")[1] - timeStart.split(":")[1]
var resultHours = differenceDays*24 + differenceHours;;
if (differenceMins < 0) {
resultHours--;
differenceMins = 60 + differenceMins; // differenceMins is negative
}
if (resultHours < 0) resultHours = resultHours + 7*24; //(this is if a you calculate the time between for example Monday 16:00 and Monday 12:00)
document.write(resultHours + " hour(s) and " + differenceMins + " minutes."); //output
For Example :
var dte = new DateTime(2012, 12, 26,1,0,0);
var dte2 = new DateTime(2012, 12, 27, 18, 5, 0);
var totalHours = (int) dte2.Subtract(dte).TotalHours;
var totalMin = dte2.AddHours(-totalHours).Subtract(dte).TotalMinutes;
Console.WriteLine(totalHours.ToString());
Console.WriteLine(totalMin.ToString());

JavaScript calculate the day of the year (1 - 366)

How do I use JavaScript to calculate the day of the year, from 1 - 366?
For example:
January 3 should be 3.
February 1 should be 32.
Following OP's edit:
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
Edit: The code above will fail when now is a date in between march 26th and October 29th andnow's time is before 1AM (eg 00:59:59). This is due to the code not taking daylight savings time into account. You should compensate for this:
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
console.log('Day of year: ' + day);
I find it very interesting that no one considered using UTC since it is not subject to DST. Therefore, I propose the following:
function daysIntoYear(date){
return (Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) - Date.UTC(date.getFullYear(), 0, 0)) / 24 / 60 / 60 / 1000;
}
You can test it with the following:
[new Date(2016,0,1), new Date(2016,1,1), new Date(2016,2,1), new Date(2016,5,1), new Date(2016,11,31)]
.forEach(d =>
console.log(`${d.toLocaleDateString()} is ${daysIntoYear(d)} days into the year`));
Which outputs for the leap year 2016 (verified using http://www.epochconverter.com/days/2016):
1/1/2016 is 1 days into the year
2/1/2016 is 32 days into the year
3/1/2016 is 61 days into the year
6/1/2016 is 153 days into the year
12/31/2016 is 366 days into the year
This works across Daylight Savings Time changes in all countries (the "noon" one above doesn't work in Australia):
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if((year & 3) != 0) return false;
return ((year % 100) != 0 || (year % 400) == 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
};
Date.prototype.dayOfYear= function(){
var j1= new Date(this);
j1.setMonth(0, 0);
return Math.round((this-j1)/8.64e7);
}
alert(new Date().dayOfYear())
Luckily this question doesn't specify if the number of the current day is required, leaving room for this answer.
Also some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's Date object covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.
So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year 0 exists and is a leap year and negative years are supported) day of the year based on year, month and day.
Note that in AD/BC notation, year 0 AD/BC does not exist: instead year 1 BC is the leap-year! IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!!
I modified (for javascript) the short-circuit bitmask-modulo leapYear algorithm and came up with a magic number to do a bit-wise lookup of offsets (that excludes jan and feb, thus needing 10 * 3 bits (30 bits is less than 31 bits, so we can safely save another character on the bitshift instead of >>>)).
Note that neither month or day may be 0. That means that if you need this equation just for the current day (feeding it using .getMonth()) you just need to remove the -- from --m.
Note this assumes a valid date (although error-checking is just some characters more).
function dayNo(y,m,d){
return --m*31-(m>1?(1054267675>>m*3-6&7)-(y&3||!(y%25)&&y&15?0:1):0)+d;
}
<!-- some examples for the snippet -->
<input type=text value="(-)Y-M-D" onblur="
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);
" /><span></span>
<br><hr><br>
<button onclick="
var d=new Date();
this.nextSibling.innerHTML=dayNo(d.getFullYear(), d.getMonth()+1, d.getDate()) + ' Day(s)';
">get current dayno:</button><span></span>
Here is the version with correct range-validation.
function dayNo(y,m,d){
return --m>=0 && m<12 && d>0 && d<29+(
4*(y=y&3||!(y%25)&&y&15?0:1)+15662003>>m*2&3
) && m*31-(m>1?(1054267675>>m*3-6&7)-y:0)+d;
}
<!-- some examples for the snippet -->
<input type=text value="(-)Y-M-D" onblur="
var d=this.value.match(/(-?\d+)[^\d]+(\d\d?)[^\d]+(\d\d?)/)||[];
this.nextSibling.innerHTML=' Day: ' + dayNo(+d[1], +d[2], +d[3]);
" /><span></span>
Again, one line, but I split it into 3 lines for readability (and following explanation).
The last line is identical to the function above, however the (identical) leapYear algorithm is moved to a previous short-circuit section (before the day-number calculation), because it is also needed to know how much days a month has in a given (leap) year.
The middle line calculates the correct offset number (for max number of days) for a given month in a given (leap)year using another magic number: since 31-28=3 and 3 is just 2 bits, then 12*2=24 bits, we can store all 12 months. Since addition can be faster then subtraction, we add the offset (instead of subtract it from 31). To avoid a leap-year decision-branch for February, we modify that magic lookup-number on the fly.
That leaves us with the (pretty obvious) first line: it checks that month and date are within valid bounds and ensures us with a false return value on range error (note that this function also should not be able to return 0, because 1 jan 0000 is still day 1.), providing easy error-checking: if(r=dayNo(/*y, m, d*/)){}.
If used this way (where month and day may not be 0), then one can change --m>=0 && m<12 to m>0 && --m<12 (saving another char).
The reason I typed the snippet in it's current form is that for 0-based month values, one just needs to remove the -- from --m.
Extra:
Note, don't use this day's per month algorithm if you need just max day's per month. In that case there is a more efficient algorithm (because we only need leepYear when the month is February) I posted as answer this question: What is the best way to determine the number of days in a month with javascript?.
If used moment.js, we can get or even set the day of the year.
moment().dayOfYear();
//for getting
moment().dayOfYear(Number);
//for setting
moment.js is using this code for day of year calculation
If you don't want to re-invent the wheel, you can use the excellent date-fns (node.js) library:
var getDayOfYear = require('date-fns/get_day_of_year')
var dayOfYear = getDayOfYear(new Date(2017, 1, 1)) // 1st february => 32
This is my solution:
Math.floor((Date.now() - new Date(new Date().getFullYear(), 0, 0)) / 86400000)
Demo:
const getDateOfYear = (date) =>
Math.floor((date.getTime() - new Date(date.getFullYear(), 0, 0)) / 864e5);
const dayOfYear = getDateOfYear(new Date());
console.log(dayOfYear);
const dayOfYear = date => {
const myDate = new Date(date);
const year = myDate.getFullYear();
const firstJan = new Date(year, 0, 1);
const differenceInMillieSeconds = myDate - firstJan;
return (differenceInMillieSeconds / (1000 * 60 * 60 * 24) + 1);
};
const result = dayOfYear("2019-2-01");
console.log(result);
Well, if I understand you correctly, you want 366 on a leap year, 365 otherwise, right? A year is a leap year if it's evenly divisible by 4 but not by 100 unless it's also divisible by 400:
function daysInYear(year) {
if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
// Leap year
return 366;
} else {
// Not a leap year
return 365;
}
}
Edit after update:
In that case, I don't think there's a built-in method; you'll need to do this:
function daysInFebruary(year) {
if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
// Leap year
return 29;
} else {
// Not a leap year
return 28;
}
}
function dateToDay(date) {
var feb = daysInFebruary(date.getFullYear());
var aggregateMonths = [0, // January
31, // February
31 + feb, // March
31 + feb + 31, // April
31 + feb + 31 + 30, // May
31 + feb + 31 + 30 + 31, // June
31 + feb + 31 + 30 + 31 + 30, // July
31 + feb + 31 + 30 + 31 + 30 + 31, // August
31 + feb + 31 + 30 + 31 + 30 + 31 + 31, // September
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30, // October
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, // November
31 + feb + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, // December
];
return aggregateMonths[date.getMonth()] + date.getDate();
}
(Yes, I actually did that without copying or pasting. If there's an easy way I'll be mad)
This is a simple way to find the current day in the year, and it should account for leap years without a problem:
Javascript:
Math.round((new Date().setHours(23) - new Date(new Date().getYear()+1900, 0, 1, 0, 0, 0))/1000/60/60/24);
Javascript in Google Apps Script:
Math.round((new Date().setHours(23) - new Date(new Date().getYear(), 0, 1, 0, 0, 0))/1000/60/60/24);
The primary action of this code is to find the number of milliseconds that have elapsed in the current year and then convert this number into days. The number of milliseconds that have elapsed in the current year can be found by subtracting the number of milliseconds of the first second of the first day of the current year, which is obtained with new Date(new Date().getYear()+1900, 0, 1, 0, 0, 0) (Javascript) or new Date(new Date().getYear(), 0, 1, 0, 0, 0) (Google Apps Script), from the milliseconds of the 23rd hour of the current day, which was found with new Date().setHours(23). The purpose of setting the current date to the 23rd hour is to ensure that the day of year is rounded correctly by Math.round().
Once you have the number of milliseconds of the current year, then you can convert this time into days by dividing by 1000 to convert milliseconds to seconds, then dividing by 60 to convert seconds to minutes, then dividing by 60 to convert minutes to hours, and finally dividing by 24 to convert hours to days.
Note: This post was edited to account for differences between JavaScript and JavaScript implemented in Google Apps Script. Also, more context was added for the answer.
I think this is more straightforward:
var date365 = 0;
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDate();
var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];
var leapYear = new Date(currentYear, 1, 29);
if (leapYear.getDate() == 29) { // If it's a leap year, changes 28 to 29
monthLength[1] = 29;
}
for ( i=0; i < currentMonth; i++ ) {
date365 = date365 + monthLength[i];
}
date365 = date365 + currentDay; // Done!
This method takes into account timezone issue and daylight saving time
function dayofyear(d) { // d is a Date object
var yn = d.getFullYear();
var mn = d.getMonth();
var dn = d.getDate();
var d1 = new Date(yn,0,1,12,0,0); // noon on Jan. 1
var d2 = new Date(yn,mn,dn,12,0,0); // noon on input date
var ddiff = Math.round((d2-d1)/864e5);
return ddiff+1;
}
(took from here)
See also this fiddle
Math.round((new Date().setHours(23) - new Date(new Date().getFullYear(), 0, 1, 0, 0, 0))/1000/86400);
further optimizes the answer.
Moreover, by changing setHours(23) or the last-but-two zero later on to another value may provide day-of-year related to another timezone.
For example, to retrieve from Europe a resource located in America.
This might be useful to those who need the day of the year as a string and have jQuery UI available.
You can use jQuery UI Datepicker:
day_of_year_string = $.datepicker.formatDate("o", new Date())
Underneath it works the same way as some of the answers already mentioned ((date_ms - first_date_of_year_ms) / ms_per_day):
function getDayOfTheYearFromDate(d) {
return Math.round((new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
- new Date(d.getFullYear(), 0, 0).getTime()) / 86400000);
}
day_of_year_int = getDayOfTheYearFromDate(new Date())
maybe help anybody
let day = (date => {
return Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
})(new Date())
I've made one that's readable and will do the trick very quickly, as well as handle JS Date objects with disparate time zones.
I've included quite a few test cases for time zones, DST, leap seconds and Leap years.
P.S. ECMA-262 ignores leap seconds, unlike UTC. If you were to convert this to a language that uses real UTC, you could just add 1 to oneDay.
// returns 1 - 366
findDayOfYear = function (date) {
var oneDay = 1000 * 60 * 60 * 24; // A day in milliseconds
var og = { // Saving original data
ts: date.getTime(),
dom: date.getDate(), // We don't need to save hours/minutes because DST is never at 12am.
month: date.getMonth()
}
date.setDate(1); // Sets Date of the Month to the 1st.
date.setMonth(0); // Months are zero based in JS's Date object
var start_ts = date.getTime(); // New Year's Midnight JS Timestamp
var diff = og.ts - start_ts;
date.setDate(og.dom); // Revert back to original date object
date.setMonth(og.month); // This method does preserve timezone
return Math.round(diff / oneDay) + 1; // Deals with DST globally. Ceil fails in Australia. Floor Fails in US.
}
// Tests
var pre_start_dst = new Date(2016, 2, 12);
var on_start_dst = new Date(2016, 2, 13);
var post_start_dst = new Date(2016, 2, 14);
var pre_end_dst_date = new Date(2016, 10, 5);
var on_end_dst_date = new Date(2016, 10, 6);
var post_end_dst_date = new Date(2016, 10, 7);
var pre_leap_second = new Date(2015, 5, 29);
var on_leap_second = new Date(2015, 5, 30);
var post_leap_second = new Date(2015, 6, 1);
// 2012 was a leap year with a leap second in june 30th
var leap_second_december31_premidnight = new Date(2012, 11, 31, 23, 59, 59, 999);
var january1 = new Date(2016, 0, 1);
var january31 = new Date(2016, 0, 31);
var december31 = new Date(2015, 11, 31);
var leap_december31 = new Date(2016, 11, 31);
alert( ""
+ "\nPre Start DST: " + findDayOfYear(pre_start_dst) + " === 72"
+ "\nOn Start DST: " + findDayOfYear(on_start_dst) + " === 73"
+ "\nPost Start DST: " + findDayOfYear(post_start_dst) + " === 74"
+ "\nPre Leap Second: " + findDayOfYear(pre_leap_second) + " === 180"
+ "\nOn Leap Second: " + findDayOfYear(on_leap_second) + " === 181"
+ "\nPost Leap Second: " + findDayOfYear(post_leap_second) + " === 182"
+ "\nPre End DST: " + findDayOfYear(pre_end_dst_date) + " === 310"
+ "\nOn End DST: " + findDayOfYear(on_end_dst_date) + " === 311"
+ "\nPost End DST: " + findDayOfYear(post_end_dst_date) + " === 312"
+ "\nJanuary 1st: " + findDayOfYear(january1) + " === 1"
+ "\nJanuary 31st: " + findDayOfYear(january31) + " === 31"
+ "\nNormal December 31st: " + findDayOfYear(december31) + " === 365"
+ "\nLeap December 31st: " + findDayOfYear(leap_december31) + " === 366"
+ "\nLast Second of Double Leap: " + findDayOfYear(leap_second_december31_premidnight) + " === 366"
);
I would like to provide a solution that does calculations adding the days for each previous month:
function getDayOfYear(date) {
var month = date.getMonth();
var year = date.getFullYear();
var days = date.getDate();
for (var i = 0; i < month; i++) {
days += new Date(year, i+1, 0).getDate();
}
return days;
}
var input = new Date(2017, 7, 5);
console.log(input);
console.log(getDayOfYear(input));
This way you don't have to manage the details of leap years and daylight saving.
A alternative using UTC timestamps. Also as others noted the day indicating 1st a month is 1 rather than 0. The month starts at 0 however.
var now = Date.now();
var year = new Date().getUTCFullYear();
var year_start = Date.UTC(year, 0, 1);
var day_length_in_ms = 1000*60*60*24;
var day_number = Math.floor((now - year_start)/day_length_in_ms)
console.log("Day of year " + day_number);
You can pass parameter as date number in setDate function:
var targetDate = new Date();
targetDate.setDate(1);
// Now we can see the expected date as: Mon Jan 01 2018 01:43:24
console.log(targetDate);
targetDate.setDate(365);
// You can see: Mon Dec 31 2018 01:44:47
console.log(targetDate)
For those among us who want a fast alternative solution.
(function(){"use strict";
function daysIntoTheYear(dateInput){
var fullYear = dateInput.getFullYear()|0;
// "Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc)
// except if it can be exactly divided by 100, then it isn't (2100, 2200, etc)
// except if it can be exactly divided by 400, then it is (2000, 2400)"
// (https://www.mathsisfun.com/leap-years.html).
var isLeapYear = ((fullYear & 3) | (fullYear/100 & 3)) === 0 ? 1 : 0;
// (fullYear & 3) = (fullYear % 4), but faster
//Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0
var fullMonth = dateInput.getMonth()|0;
return ((
// Calculate the day of the year in the Gregorian calendar
// The code below works based upon the facts of signed right shifts
// • (x) >> n: shifts n and fills in the n highest bits with 0s
// • (-x) >> n: shifts n and fills in the n highest bits with 1s
// (This assumes that x is a positive integer)
(31 & ((-fullMonth) >> 4)) + // January // (-11)>>4 = -1
((28 + isLeapYear) & ((1-fullMonth) >> 4)) + // February
(31 & ((2-fullMonth) >> 4)) + // March
(30 & ((3-fullMonth) >> 4)) + // April
(31 & ((4-fullMonth) >> 4)) + // May
(30 & ((5-fullMonth) >> 4)) + // June
(31 & ((6-fullMonth) >> 4)) + // July
(31 & ((7-fullMonth) >> 4)) + // August
(30 & ((8-fullMonth) >> 4)) + // September
(31 & ((9-fullMonth) >> 4)) + // October
(30 & ((10-fullMonth) >> 4)) + // November
// There are no months past December: the year rolls into the next.
// Thus, fullMonth is 0-based, so it will never be 12 in Javascript
(dateInput.getDate()|0) // get day of the month
)&0xffff);
}
// Demonstration:
var date = new Date(2100, 0, 1)
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))
console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);
date = new Date(1900, 0, 1);
for (var i=0; i<12; i=i+1|0, date.setMonth(date.getMonth()+1|0))
console.log(date.getMonth()+":\tday "+daysIntoTheYear(date)+"\t"+date);
// Performance Benchmark:
console.time("Speed of processing 65536 dates");
for (var i=0,month=date.getMonth()|0; i<65536; i=i+1|0)
date.setMonth(month=month+1+(daysIntoTheYear(date)|0)|0);
console.timeEnd("Speed of processing 65536 dates");
})();
The size of the months of the year and the way that Leap Years work fits perfectly into keeping our time on track with the sun. Heck, it works so perfectly that all we ever do is just adjust mere seconds here and there. Our current system of leap years has been in effect since February 24th, 1582, and will likely stay in effect for the foreseeable future.
DST, however, is very subject to change. It may be that 20 years from now, some country may offset time by a whole day or some other extreme for DST. A whole DST day will almost certainly never happen, but DST is still nevertheless very up-in-the-air and indecisive. Thus, the above solution is future proof in addition to being very very fast.
The above code snippet runs very fast. My computer can process 65536 dates in ~52ms on Chrome.
This is a solution that avoids the troublesome Date object and timezone issues, it requires that your input date be in the format "yyyy-dd-mm". If you want to change the format, then modify date_str_to_parts function:
function get_day_of_year(str_date){
var date_parts = date_str_to_parts(str_date);
var is_leap = (date_parts.year%4)==0;
var acct_for_leap = (is_leap && date_parts.month>2);
var day_of_year = 0;
var ary_months = [
0,
31, //jan
28, //feb(non leap)
31, //march
30, //april
31, //may
30, //june
31, //july
31, //aug
30, //sep
31, //oct
30, //nov
31 //dec
];
for(var i=1; i < date_parts.month; i++){
day_of_year += ary_months[i];
}
day_of_year += date_parts.date;
if( acct_for_leap ) day_of_year+=1;
return day_of_year;
}
function date_str_to_parts(str_date){
return {
"year":parseInt(str_date.substr(0,4),10),
"month":parseInt(str_date.substr(5,2),10),
"date":parseInt(str_date.substr(8,2),10)
}
}
A straightforward solution with complete explanation.
var dayOfYear = function(date) {
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const [yyyy, mm, dd] = date.split('-').map(Number);
// Checks if February has 29 days
const isLeap = (year) => new Date(year, 1, 29).getDate() === 29;
// If it's a leap year, changes 28 to 29
if (isLeap(yyyy)) daysInMonth[1] = 29;
let daysBeforeMonth = 0;
// Slice the array and exclude the current Month
for (const i of daysInMonth.slice(0, mm - 1)) {
daysBeforeMonth += i;
}
return daysBeforeMonth + dd;
};
console.log(dayOfYear('2020-1-3'));
console.log(dayOfYear('2020-2-1'));
I wrote these two javascript functions which return the day of the year (Jan 1 = 1).
Both of them account for leap years.
function dayOfTheYear() {
// for today
var M=[31,28,31,30,31,30,31,31,30,31,30,31]; var x=new Date(); var m=x.getMonth();
var y=x.getFullYear(); if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m;++i) {Y+=M[i];}
return Y+x.getDate();
}
function dayOfTheYear2(m,d,y) {
// for any day : m is 1 to 12, d is 1 to 31, y is a 4-digit year
var m,d,y; var M=[31,28,31,30,31,30,31,31,30,31,30,31];
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {++M[1];}
var Y=0; for (var i=0;i<m-1;++i) {Y+=M[i];}
return Y+d;
}
One Line:
Array.from(new Array(new Date().getMonth()), (x, i) => i).reduce((c, p, idx, array)=>{
let returnValue = c + new Date(new Date().getFullYear(), p, 0).getDate();
if(idx == array.length -1){
returnValue = returnValue + new Date().getDate();
}
return returnValue;
}, 0)
I needed a reliable (leap year and time zone resistant) algorithm for an application that makes heavy use of this feature, I found some algorithm written in the 90s and found that there is still no such efficient and stable solution here:
function dayOfYear1 (date) {
const year = date.getFullYear();
const month = date.getMonth()+1;
const day = date.getDate();
const N1 = Math.floor(275 * month / 9);
const N2 = Math.floor((month + 9) / 12);
const N3 = (1 + Math.floor((year - 4 * Math.floor(year / 4) + 2) / 3));
const N = N1 - (N2 * N3) + day - 30;
return N;
}
Algorithm works correctly in leap years, it does not depend on time zones with Date() and on top of that it is more efficient than any of the lower ones:
function dayOfYear2 (date) {
const monthsDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
let N = monthsDays[month] + day;
if ( month>1 && year%4==0 )
N++;
return N;
}
function dayOfYear3 (date) {
const yearDate = new Date(date.getFullYear(), 0, 0);
const timeZoneDiff = yearDate.getTimezoneOffset() - date.getTimezoneOffset();
const N = Math.floor(((date - yearDate )/1000/60 + timeZoneDiff)/60/24);
return N;
}
All of them are correct and work under the conditions mentioned above.
Performance comparison in 100k loop:
dayOfYear1 - 15 ms
dayOfYear2 - 17 ms
dayOfYear3 - 80 ms
It always get's me worried when mixing maths with date functions (it's so easy to miss some leap year other detail). Say you have:
var d = new Date();
I would suggest using the following, days will be saved in day:
for(var day = d.getDate(); d.getMonth(); day += d.getDate())
d.setDate(0);
Can't see any reason why this wouldn't work just fine (and I wouldn't be so worried about the few iterations since this will not be used so intensively).

Categories

Resources