Countdown to next month - progress bar - JavaScript - javascript

I am very new to HTML and have found a few tutorials online on how to make progress bars for various uses - but have found nothing for long time countdowns; (One day to another day).
I want a progress bar countdown to next month. E.g, if today was April 15, the progress bar would be 50% filled, since the next month is 15 days away.
Ideally, the countdown will start on the left using a specific time on a certain day as a starting point and move toward the right as time continues - arriving at the end when the countdown is up and the time on the specific second date has arrived. The time should also be specific to EST not the local time on the computer.
Any help with this would be greatly appreciated thanks!!

You'll have to:
Calculate how many days until the next month.
This is achieved by getting the current date (via the Date constructor) and getting the current month (with Date.getMonth()), then constructing a new date via the Date constructor and adding 1 to the current month index. This is what nextMonth is in the example below.
Calculate the number of days between the next month and the current day
This is slightly more tricky. You'll have to get the millisecond difference between the two dates (by subtracting the results returned by Date.getTime() for the current date and the next month), then dividing by 1000 (to get the seconds), 60 (for minutes), 60 again (for hours), and finally dividing by 24 (for days).
Calculate the number of days in the current month
This is done by setting the month to one month later than the current month, and the date to 0. Why? When 0 is provided for dayValue, the date will be set to the last day of the previous month, and since we set the month to the next month, it will return the last day of the current month. Calling getDate() then returns the day of the month.
To make the progress bar, you can simply use the <progress> element. Set the maximum to the number of days in the current month and the value to the number of days minus the days until the next month (how many days have passed in this month so far).
const now = new Date();
const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const diffDays = Math.ceil(Math.abs(nextMonth.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
now.setMonth(now.getMonth() + 1);
now.setDate(0);
const daysInCurrentMonth = now.getDate();
progress.max = daysInCurrentMonth;
progress.value = daysInCurrentMonth - diffDays;
/* below for debug purposes only */
console.log('Days in current month: ' + daysInCurrentMonth);
console.log('Days until next month: ' + diffDays);
#progress {
width: 100%;
}
<progress id="progress"></progress>

Related

Date appears to be changing time zone from daylight to standard upon calculation

I have a jQuery range slider that is supposed to increase and decrease the date range by a week with each value. When incrementing past a certain point (November 1st in my example) the time zone changes from daylight to standard. I assume it has something to do with the way I'm calculating the new date but I can't seem to figure out what it is.
I calculate it with:
new Date(minDate.getTime() + (sliderValue * 7) * 1000 * 60 * 60 * 24)
Here's an example fiddle: https://jsfiddle.net/aedryan/f4pvg84e/
Your code is actually working fine. The reason it changes after November 1 is because we switch from Eastern Daylight Time (EDT) to Eastern Standard Time on that date - in both cases you are representing the eastern time zone. Btw, for the future this is a nice way of adding days to a date:
/**
* extends the functionality of the Date() object to include a function called addDays that adds days to
* a javascript date based on an integer
* #param days
* #returns {Date}
*/
Date.prototype.addDays = function(days){
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
You were calculating days by millisecond. However, November 1st was in fact day light savings (welcome to the wonderful world of time culture). As a result your times are off by 1 hour and that means you count 23 hours for one day and only get +6.
As opposed to making these changes by millisecond, simply add the days. This can be done easily in JavaScript as when the days extend past the amount available that month it just returns the adjusted date. That means you can use this for your newDate forumla
var newDate = new Date(2015, 7, 23+(ui.value*7));
Which looks like this: https://jsfiddle.net/u2h261ka/

Why is this PDF javascript Date being incorrectly calculated only once a year?

I have an interesting result from the javascript in an Acrobat PDF Form
I have a series of date form fields. The first field is for user entry and the remaining fields are calculated by javascript, each field incremented by one day.
The code is:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
var dateStartMilli = dateStart.getTime();
var oneDay = 24 * 60 * 60 * 1000 * 1; // number of milliseconds in one day
var dateMilli = dateStartMilli + oneDay;
var date = new Date(dateMilli);
event.value = util.printd("dd/mm/yy",date);
} else { event.value = "" }
The issue is if I input 05/04/15 in to the user field the result is 05/04/15 (same, wrong) while any other date of the year correctly increments by one day (ie 25/10/15 gives 26/10/15, 14/2/15 gives 15/2/15 etc)
The same error occurs on the 3rd of April 2016, 2nd of April 2017, etc (ie each year)
I have a fortnight (14) of these incrementing fields, each incrementing the date from the previous calculated field with the same javascript as above ("userField" is changed to date2, date3, date4 etc). What is very strange is that the next field that increments off the second of the two 05/04/15 correctly returns 06/04/15 and there isn't an issue after that.
Does anyone know why this might be?!
That doesn't happen on my browser's JavaScript engine and/or in my locale, so it must be an Acrobat thing or that date may be special in your locale (e.g., DST).
In any case, that's not the correct way to add one day to a JavaScript date, not least because some days have more than that many milliseconds and some have less (transitioning to and from DST).
The correct way is to use getDate and setDate:
var strStart = this.getField("userField").value;
if(strStart.length > 0) {
var dateStart = util.scand("dd/mm/yy",strStart);
dateStart.setDate(dateStart.getDate() + 1); // Add one day
event.value = util.printd("dd/mm/yy",dateStart);
} else { event.value = "" }
setDate is smart enough to handle it if you go past the end of the month (per specification).
If it's DST-related, the above will fix it. If it's some weird Acrobat thing, perhaps it will work around it. Either way, it's how this should be done.
Let me guess, that's the day daylight savings starts in your locale? 24 hours after midnight is not always the next day, because some days have 25 hours.
Approaches that come to my head:
manipulate the day. (This is easy if Acrobat allows dates like the 32nd of January, because oyu can just increment the day. Otherwise, maybe don't bother because leap years aren't much better than DST.)
don't start from midnight. If you never use the hour and minute within the day, don't pin your day at the strike of midnight, but at, say, 3am. After a change in DST status, later days in your fortnight might register as 2am or 4am, but as long as you're only using the day…

Javascript Day Increment in Seconds rolls over at 5:00PM

I am trying to keep track of the days since the birth of my program in epoch days. So, I I give my program:
epochProgram = 15622 // epoch day number that this program was born.
I then get the current time and divide by 1000 to make it seconds. Then I take that and divide it by the number of seconds per a day which is 86400 to convert it to the number of days today since epoch. I then subtract the program epoch birthday number from today's epoch number to see how many days have lapse since the birth of the program.
dateObj = new Date();
var biz = parseInt(dateObj.getTime()/1000));
biz = biz/86400-epochProgram;
Lets say a few days have past and biz=6.30. My issue is this:
12:00 am is at 6.30, at 5:00PM biz=7.0, and at 11:PM, biz=7.2.
Why does the tenths .# digit work as .3 is the start of the say and .2 is the end of the day? What could I do to fix this so I can have a correct day increment?
PS: this is local Pacific time.
Subtract the timezone offset:
var biz = (dateObj.getTime() - dateObj.getTimezoneOffset() * 6e4) / 1000 >>> 0;

Calculating Jday(Julian Day) in javascript

I have requirement to calculate jday in javascript , for doing client side validation , Can any one help me how to calculate JDAY in javascript or script to change given JDAY to actual date or vice versa .
To know what is JDay ,I found the following site ,
http://www.pauahtun.org/Software/jday.1.html
Am also refering the below site for calculation which is mentioned in JAVA
http://www.rgagnon.com/javadetails/java-0506.html
Thank you in advance
Julian Day
The Julian Day is the number of elapsed days since the beginning of a cycle of 7980 years.
Invented in 1583 by Joseph Scaliger, the purpose of the system is to make it easy to compute an integer (whole number) difference between one calendar date and another calendar date.
The 7980 year cycle was derived by combining several traditional time cycles (solar, lunar, and a particular Roman tax cycle) for which 7980 was a common multiple.
The starting point for the first Julian cycle began on January 1, 4713 B.C. at noon GMT, and will end on January 22, 3268 at noon GMT, exactly 7980 whole days later.
As an example, the Julian day number for January 1, 2016 was 2,457,389, which is the number of days since January 1, 4713 B.C. at that day.
How to calculate it
As we know that Unix time is the number of seconds since 00:00:00 UTC, January 1, 1970, not counting leap seconds, and also called Epoch, we can use some math to calculate the Julian Day when we already have the Unix time.
GMT and UTC share the same current time in practice, so for this, there should be no difference.
To start with, we need to know the number of days from when the Julian cycle began, until Unix timestamps began.
In other words, the number of days from January 1, 4713 B.C. at 12:00:00 GMT, until January 1, 1970 at 00:00:00 UTC.
Having this set number of days, that never change, we can just add the number of days from January 1, 1970 until today, which is what Javascript returns anyway, to get the Julian Day.
Without adding up all those years, but simply by searching the web, it tells us that the difference in days between the year 4713 B.C. and 1970 A.D. is 2440588 days, and because the Julian Cycle began at noon, not at midnight, we have to subtract exactly half a day, making it 2440587.5 days.
So what we have now is 2440587.5 days + UNIX TIME in days === Julian Day
With some simple math we can figure out that a day is 86,400 seconds long, and the Unix timestamp is in milliseconds when using Javascript, so UNIX TIME / 86400000 would get us the number of days since Thursday, 1 January 1970, until today.
Now for just the day, we wanted the whole number of days, and not the fractional, and can just round it down to the closes whole day, doing something like
Math.floor((UNIX TIME / 86400000) + 2440587.5);
Julian Date
Sometimes in programming, a "Julian Date" has come to mean the number of days since the year started, for instance June 1, 2016 would be 152 days into that year etc.
The correct use of "Julian Date" is a Julian Day with a timestamp added as a fractional part of the day.
Taking the example at the top of this answer, where January 1, 2016 was the Julian Day 2,457,389 , we can add a time to that.
The Julian Day starts at noon, with no fractional time added, and so at midnight it would be 2457389.5 and at 18:00, or six hours after noon, it would be 2457389.25, adding "half a day", "quarter of a day" etc.
Calculating it, again
This means 0.1 Julian Date is the same as 24 hours divided by 10, or 24 / 10 === 2.4 hours, or in other words, Julian Day timestamps are fractional with decimals (one tenth of a day etc).
Lets look at some Javascript functions, firstly the Date constructor.
Javascript only has access to the local time on the computer it runs on, so when we do new Date() it does not neccessarely create an UTC date, even if UNIX time is in UTC, new Date gives you the number of seconds from epoch until whatever local time your computer has, and does not take your timezone into consideration.
Javascript does however have Date.UTC, which would return the date in UTC format, lets check the difference, and this will of course differ according to the timezone you've set the local system to.
var regular_date = new Date(2016, 1, 1, 0, 0, 0);
var UTC_date = Date.UTC(2016, 1, 1, 0, 0, 0);
var difference = UTC_date - regular_date;
document.body.innerHTML = 'The difference between your local time and UTC is ' +(difference/1000)+ ' seconds';
Remember the part at the begin of this chapter, about 0.1 Julian Date being the same as 24 hours divided by 10, or 24 / 10 === 2.4 hours, well, 2.4 hours is 144 minutes, and now lets look quickly at Javascripts getTimezoneOffset() method, the docs say
The getTimezoneOffset() method returns the time-zone offset from UTC,
in minutes, for the current locale.
So, it returns the offset for the systems timezone in minutes, that's interesting as most javascript methods that deal with dates returns milliseconds.
We know that a 1/10 of a day is 144 minutes, so 10/10, or a whole day, would be 1440 minutes, so we could use some math to counteract the local systems timezone, given in minutes, and divide it by the number of minutes in a day, to get the correct fractional value
So now we have
2440587.5 days + UNIX TIME in days === Julian Day
and we know Javascripts Date constructor doesn't really use UTC for the current date, but the system time, so we have to have
TIMEZONEOFFSET / 1440
joining them together we would get
(JAVASCRIPT TIME / 86400000) - (TIMEZONEOFFSET / 1440) + 2440587.5
// ^^ days since epoch ^^ ^^ subtract offset ^^ ^^days from 4713 B.C. to 1970 A.D.
Translating that to javascript would be
var date = new Date(); // a new date
var time = date.getTime(); // the timestamp, not neccessarely using UTC as current time
var julian_day = (time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5);
Now this is what we should use to get the Julian Day as well, taking measures to remove the timezone offset, and of course without the fractional time part of the Julian Date.
We would do this by simpy rounding it down to the closest whole integer
var julian_date = Math.floor((time / 86400000) - (date.getTimezoneOffset()/1440) + 2440587.5));
And it's time for my original answer to this question, before I made this extremely long edit to explain why this is the correct approach, after complaints in the comment field.
Date.prototype.getJulian = function() {
return Math.floor((this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5);
}
var today = new Date(); //set any date
var julian = today.getJulian(); //get Julian counterpart
console.log(julian)
.as-console-wrapper {top:0}
And the same with the fracional part
Date.prototype.getJulian = function() {
return (this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5;
}
var today = new Date(); //set any date
var julian = today.getJulian(); //get Julian counterpart
console.log(julian)
.as-console-wrapper { top: 0 }
And to finish of, an example showing why
new Date().getTime()/86400000 + 2440587.5
doesn't work, at least not if your system time is set to a timezone with an offset, i.e. anything other than GMT
// the correct approach
Date.prototype.getJulian = function() {
return (this / 86400000) - (this.getTimezoneOffset() / 1440) + 2440587.5;
}
// the simple approach, that does not take the timezone into consideration
Date.prototype.notReallyJulian = function() {
return this.getTime()/86400000 + 2440587.5;
}
// --------------
// remember how 18:00 should return a fractional 0.25 etc
var date = new Date(2016, 0, 1, 18, 0, 0, 0);
// ^ ^ ^ ^ ^ ^ ^
// year month date hour min sec milli
var julian = date.getJulian(); //get Julian date
var maybe = date.notReallyJulian(); // not so much
console.log(julian); // always returns 2457389.25
console.log(maybe); // returns different fractions, depending on timezone offset
.as-console-wrapper { top: 0 }
new Date().getTime()/86400000 + 2440587.5
will get the unix time stamp, convert it to days and add the JD of 1970-01-01, which is the epoch of the unix time stamp.
This is what astronomers call julian date. It is well defined. Since neither Unix time stamp nor JD take leap seconds into account that does not reduce the accuracy. Note that JD need not be in timezone UTC (but usually is). This answer gives you the JD in timezone UTC.
According to wikipedia:
a = (14 - month) / 12
y = year + 4800 - a
m = month + 12a - 3
JDN = day + (153m + 2) / 5 + 365y + y/4 - y/100 + y/400 - 32045
If you're having a more specific problem with the implementation, provide those details in the question so we can help further.
NOTE : This is not correct because the "floor brackets" on Wiki were forgotten here.
The correct formulas are:
a = Int((14 - Month) / 12)
y = Year + 4800 - a
m = Month + 12 * a - 3
JDN = Day + Int((153 * m + 2) / 5) + 365 * y + Int(y / 4) - Int(y / 100) + Int(y / 400) - 32045
JD =>
const millisecondsSince1970Now = new Date+0
const julianDayNow = 2440587.5+new Date/864e5
const dateNow = new Date((julianDayNow-2440587.5)*864e5)
There seems to be confusion about what a Julian-Day is, and how to calculate one.
Javascript time is measured as GMT/UTC milliseconds UInt64 from Jan 1, 1970 at midnight.
The Month, Day, Year aspects of the JavaScript Date function are all implemented using Gregorian Calendar rules. But Julian "Days" are unaffected by that; however mapping a "day-count" to a Julian Month, Day, Year would be.
Calculating Julian-Day conversions are therefore a relative day count from that point in time (Jan 1, 1970 GMT/UTC Gregorian).
The Julian-Day for Jan 1, 1970 is 2440587.5 (0.5 because JulianDays started at NOON).
The 864e5 constant is JavaScript notation for 86,400,000 (milliseconds/day).
The only complexities are in calculating Julian dates (days) prior to adoption of the 1582 Gregorian calendar whose changes mandated from Pope Gregory were to correct for Leap Year drift inaccuracies affecting Easter. It took until around 1752 to be fully adopted throughout most countries in the world which were using the Julian Calendar system or a derivative (Russia and China took until the 20th century).
And the more egregious errors in the first 60 years of Julian date implementation from Julius Caesar's 46BC "reform" mandate where priests made mistakes and people misunderstood as they folded a 14/15 month calendar. (hence errors in many religious dates and times of that period).
🎪 None of which applies in JavaScript computation of Julian Day values.
See also: (from AfEE EdgeS/EdgeShell scripting core notes)
Astronomy Answers - Julian Day Number (multi-calendrical conversions)
Julian calendar
Atomic Clocks
JavaScript operator precedence
Microsoft FILETIME relative to 1/1/1601 epoch units: 10^-7 (100ns)
UUID/GUIDs timestamp formats - useful for time-date conversion also
"Leap Second" details
There is a separate subtlety "leap-second" which applies to astronomical calculations and the use of atomic clocks that has to do with earth orbital path and rotational drift.
i.e., 86,400.000 seconds per day needs "adjustment" to keep calendars (TimeZones, GPS satellites) in sync as it is currently 86,400.002.
It seems that the final code given in the accepted answer is wrong. Check the "official" online calculator at US Naval Observarory website:
http://aa.usno.navy.mil/data/docs/JulianDate.php
If someone knows the correct answer to a answer time and calendar, it's USNO.
Additionally, there is an npm package for this:
julian
Convert between Date object and Julian dates used in astronomy and history
var julian = require('julian');
var now = new Date(); // Let's say it's Thu, 21 Nov 2013 10:47:02 GMT
var jd = '';
console.log(jd = julian(now)); // -> '2456617.949335'
console.log(julian.toDate(jd)); // -> Timestamp above in local TZ
https://www.npmjs.com/package/julian
Whatever you do, DON'T USE getTimezoneOffset() on dates before a change of policy in the current Locale, it's completely broken in the past (it doesn't apply iana database rules).
For example, if I enter (UTC date 1st of october 1995 at 00:00:00):
var d=new Date(Date.UTC(1995, 9, 1, 0, 0, 0)); console.log(d.toLocaleString()); console.log(d.getTimezoneOffset());
in the javascript console in Chrome, it prints (I'm in France):
01/10/1995 at 01:00:00 <= this is winter time, +1:00 from UTC
-120 <= BUT this is summer time offset (should be -60 for winter)
Between 1973 and 1995 (included), DST (-120) terminated last Sunday of September, hence for 1st of October 1995, getTimezoneOffset() should return -60, not -120. Note that the formatted date is right (01:00:00 is the expected -60).
Same result in Firefox, but in IE and Edge, it's worse, even the formatted date is wrong (01‎/‎10‎/‎1995‎ ‎02‎:‎00‎:‎00, matching the bad -120 result of getTimezoneOffset()). Whatever the browser (of these 4), getTimezoneOffset() uses the current rules rather than those of the considered date.
Variation on the same problem when DST didn't applied in France (1946-1975), Chrome console:
d=new Date(Date.UTC(1970, 6, 1, 0, 0, 0)); console.log(d.toLocaleString()); console.log(d.getTimezoneOffset());
displayed:
‎01‎/‎07‎/‎1970‎ ‎01:‎00‎:‎00 <= ok, no DST in june 1970, +1:00
-120 <= same problem, should be -60 here too
And also, same thing in Firefox, worse in IE/Edge (01‎/‎07‎/‎1970‎ ‎02:‎00‎:‎00).
I did this for equinox and solistice. You can use the function for any Julian date.
It returns the Julian date in the calender date format: day/month.
Include year and you can format it anyway you want.
It's all there, year, month, day.
Since Equinox and Solistice are time stamps rather than dates, my dates in the code comes back as decimals, hence "day = k.toFixed(0);". For any other Julian date it should be day = k;
// For the HTML-page
<script src="../js/meuusjs.1.0.3.min.js"></script>
<script src="../js/Astro.Solistice.js"></script>
// Javascript, Julian Date to Calender Date
function jdat (jdag) {
var jd, year, month, day, l, n, i, j, k;
jd = jdag;
l = jd + 68569;
n = Math.floor(Math.floor(4 * l) / 146097);
l = l - Math.floor((146097 * n + 3) / 4);
i = Math.floor(4000 * (l + 1) / 1461001);
l = l - Math.floor(1461 * i / 4) + 31;
j = Math.floor(80 * l / 2447);
k = l - Math.floor(2447 * j / 80);
l = Math.floor(j / 11);
j = j + 2 - 12 * l;
i = 100 * (n - 49) + i + l;
year = i;
month = j;
day = k.toFixed(0); // Integer
dat = day.toString() + "/" + month.toString(); // Format anyway you want.
return dat;
}
// Below is only for Equinox and Solistice. Just skip if not relevant.
// Vernal Equinox
var jv = A.Solistice.march(year); // (year) predefined, today.getFullYear()
var vdag = jdat(jv);
// Summer Solistice
var js = A.Solistice.june(year);
var ssol = jdat(js);
//Autumnal Equinox
var jh = A.Solistice.september(year);
var hdag = jdat(jh);
// Winter Solistice
var jw = A.Solistice.december(year);
var vsol = jdat(jw);

How to determine if it is day or night in Javascript? [duplicate]

This question already has answers here:
Calculating sunrise/sunset times in Javascript
(4 answers)
Closed 1 year ago.
Im wanting to apply different CSS sheets to my site depending on the time of the browser. e.g if its day time, display day.css or night.css for night.
I can do this with PHP but it is based on the server time, not the browsers local time.
Is there a way to tell the time in javascript? I'm probably going to use jQuery to simply initiate the css once its worked out.
var hr = (new Date()).getHours(); //get hours of the day in 24Hr format (0-23)
Depending on your definition of day/night, perform your magic :)
PS: If your day/night starts not at the exact hour, you can try getMinutes().
I use this logic:
const hours = new Date().getHours()
const isDayTime = hours > 6 && hours < 20
(new Date).getHours()
will get the local hour of the time (0-23) of the client. Based on that value, swap the stylesheet for the page. I would set the day stylesheet as the default and swap it out when necessary.
My initial thought is that you would want to perform this operation as soon as possible on the client to avoid any potential browser reflow.
For this to work you’ll need to know the location of the client, the local sunrise and sunset time and the day of the year. Only locations at the equator have an almost constant 12 hour of day light all the year around.
This other answer on StackOverflow provides a good answer:
Calculating sunrise/sunset times in Javascript
Fun question. I wanted to give it a try and come up with something totally different than what was proposed so far. This is what I got:
function isDay() {
return (Date.now() + 60000 * new Date().getTimezoneOffset() + 21600000) % 86400000 / 3600000 > 12;
}
It will return true if it's between 6 AM and 6 PM, or false otherwise.
Breaking down into parts:
Date.now() returns UTC epoch in milliseconds;
new Date().getTimezoneOffset() gets local time zone, in minutes, and 60000 just converts it to milliseconds;
21600000 represents 6 hours in milliseconds. This is a hack to pretend each day starts at 6 AM (will be explained in the end);
86400000 is how many milliseconds there is in a day, so X % 86400000 will return how many milliseconds have passed since the current day begun; since we added 6 hours in the previous step, this is actually counting millis since 6 AM;
we divide that result by 3600000 (number of milliseconds in an hour) to find out how many hours have passed since the day begun;
since we added 6 hours to our clock, 6 AM is now 12 PM, and 6 PM is actually midnight. This is why the function checks to see if the value is greater than 12; if it is, it must be between 6 AM and 6 PM right now. Anything earlier than 6 AM or later than 6 PM becomes less than 12, according to that formula.
Of course, the same can be accomplished with:
function isDay() {
const hours = (new Date()).getHours();
return (hours >= 6 && hours < 18);
}
But that is not even half as fun :-D

Categories