Date subtraction in JavaScript - javascript

I have two text boxes which accept Start Date and End Date respectively, in format YYYY/MM/DD.
I need to alert the user if he selects an end date that exceeds the start date by 50 days.
Here's what I have so far:
var startDate = new Date(document.getElementsByName('MYSTARTDATE').value);
var endDate = new Date(document.getElementsByName('MYENDDATE').value);
if ((endDate - startDate) > 50)
{
alert('End date exceeds specification');
return false;
}
Just as an example, when I select Start Date as 2012/01/22 and End Date as 2012/02/29
startDate = 'Sun Jan 22 00:00:00 UTC +0530 2012'
endDate = 'Wed Feb 29 00:00:00 UTC +0530 2012'
And the result for endDate - startDate is 3283200000, instead of 38.What am I doing wrong?

3283200000 is 38 days in milliseconds.
38 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
Also, there are 38 days between those two dates, not 39.
An easy solution is to have a variable (constant really) defined as the number of milliseconds in a day:
var days = 24*60*60*1000;
And use that variable as a "unit" in your comparison:
if ((endDate - startDate) > 50*days) {
...
}

The solution by Jeff B is incorrect, because of daylight savings time. If the the startDate is, say, on October 31, and the endDate is on December 20, the amount of time that has actually elapsed between those two times is 50 days plus 1 hour, not 50 days. This is especially bad if your program doesn't care about the time of day and sets all times at midnight - in that case, all calculations would be off by one for the entire winter.
Part of the correct way to subtract dates is to instantiate a new Date object for each of the times, and then use an Array with the number of days in each month to compute how many days have actually passed.
But to make things worse, the dates that Europe changes the clocks are different than the dates that the clocks are changed in New York. Therefore, timezone alone is not sufficient to determine how many days have elapsed; location is also necessary.
Daylight savings time adds significant complexity to date handling. In my website, the function needed to accurately compute the number of days passed is nearly a hundred lines. The actual complexity is dependent on whether the calculations are client side or server side or both and who is viewing the data.

Related

Using moment.js timezone to get day extremes in another timezone (but the answer in UTC)

I want to work out the day extremes (midnight to midnight) for a particular day, where that day is a whole number of days relative to now (i.e. relative to Date.now())... but for a different timezone to UTC. But I want the answer (midnight times) back in UTC time (in milliseconds, similar to what you get with Date.now()), so that I can feed those to an API that expects UTC times, to get the exact right time range of data. I have tried to use moment.js timezone but am getting horribly stuck... I found this answer but it doesn't work in a different timezone.
I suggest you consider using Luxon, which is essentially the replacement for moment.js.
The algorithm is create a date for now in the required representative location, subtract the required number of days, then set to the start of day, then get the time value, e.g.
let DateTime = luxon.DateTime;
// Create date for 00:00:00 3 days ago in Denver
let d = DateTime.local() // Create a date
.setZone('America/Denver') // Set to Denver
.minus({days:3}) // Subtract 3 days
.startOf('day'); // Set to start of day
// Create date for end of day
let e = d.endOf('day');
// Denver 3 days ago at start and end of day
console.log('Start of day: ' + d.toISO() + '\nTime value : ' + d.ts);
console.log('End of day: ' + e.toISO() + '\ntime value : ' + e.ts);
<script src="https://cdn.jsdelivr.net/npm/luxon#1.24.1/build/global/luxon.min.js"></script>
Note that 3 days ago in Denver might be a different date to 3 days ago in the host system because of the offset differences. E.g in Sydney, Australia at 9 am on 20 July it's 5 pm on 19 July in Denver, so subtracting 3 days in Sydney is 17 July but 16 July in Denver.
Moment will allow you to do this fairly easily:
function getUTCMidnightMillis(timezone, days_ago) {
return moment() // Current time.
.tz(timezone) // Convert to desired timezone.
.subtract(days_ago, 'days') // Go back x days.
.startOf('day') // Get start of day, aka Midnight!
.utc() // Convert value into UTC.
.valueOf() // Return milliseconds since unix epoch.
}
console.log("Midnight in Denver:", getUTCMidnightMillis("America/Denver", 0))
console.log("Midnight in New York:", getUTCMidnightMillis("America/New_York", 0))
Which produces the output:
Midnight in Denver: 1594274400000
Midnight in New York: 1594267200000
And indeed, you can verify that is correct:
new Date(1594274400000).toISOString()
// Produces: "2020-07-09T06:00:00.000Z"
For the 9th of July, 2020, we observe daylight savings in Denver, making our UTC offset -6 hours. So the above timestamp (6:00am UTC) is the same moment at which it is midnight in Denver.

UTC time from new Date() using JS

I have checked so many places but could not find a proper answer. I have to get current time in UTC and then subtract few days (say 2 days). So if today is 25th March, I would like to get data of past 2 days starting from 23rd March 00:00 hours GMT.
I can get individual hours and minutes in GMT. But the moment I do new Date() it gives me in local timestamp. Normally I would subtract the current GMT hours and minutes from current time and the number of days I have to subtract.
But when I do a new Date() instead of GMT I get local time. I can do toUTCString() but that is after getting the time in my local time format. If I subtract my local time too then my code won't work universally.
So I need to get the new Date() function in UTC format. I checked a lot of places but nothing seems to work.
The getTime method will return a number representing the milliseconds elapsed from the epoch (1 January 1970 00:00:00 UTC). This method always uses UTC for time representation.
Then you could subtract 2 days and get another Date instance:
var timestamp = new Date().getTime();
timestamp = timestamp - 2 * 24 * 60 * 60 * 1000;
var newDate = new Date(timestamp);
I recommend you use Moment.js to operate with Dates.
In particular adding or subtracting dates is very easy using this library, for example:
moment().subtract(2, 'days')
If you want to do it natively, there are many ways to do it, but one of them is this:
const d = new Date();
d.setDate(d.getDate() - 2);
About UTC date:
But the moment I do new Date() it gives me in local timestamp
That's just a string representation, that is different depending on the environment. Dates are stored internally in UTC, so there is no problem using new Date() and operating with it.

How to create a timestamp from date and time

i have a datepicker and some time slots in my view. the time slots are checkboxes and the value of checkbox should be a timestamp which i aim to get by combining the value from datepicker and the checkbox slot that was checked by the user. Is there any way to do this using javascript of jquery.
Example:
$('#inline_datepicker').datepicker("getDate") + "02:30PM" => create timestamp
I'm not clear on exactly what you're looking for here, but to just get a basic timestamp in string format using milliseconds (from Jan. 1, 1970 at midnight, as is the standard) you can just do this using vanilla javascript:
var timestamp = new Date(2014,1,3,18).getTime();
The format is yyyy/mm/dd/hh and it is zero based and the hours use a 24 hour clock, also called military time if you are from the United States. The above example gives the timestamp for February 4, 2014 at 6pm.
You can then always add time to the time stamp by adding time to that value, too. 1 day is 24 hours, one hour is 60 minutes, one minute is 60 seconds, and one second is 1000 milliseconds. That means after creating a timestamp, if you wanted to add 4 days, 13 hours, 49 minutes, and 6 seconds, you could do this:
var timestamp = new Date(2014,1,3,18).getTime();
timestamp += (((4*24+13)*60+49)*60+6)*1000;
Finally, you can always convert back to a human-readable timestamp using the .toUTCString() method in conjunction with creating a new Date object. The final code would read as such:
var timestamp= new Date(2014,1,3,18).getTime();
console.log(new Date(timestamp).toUTCString());
/* Outputs "Sun, 04 Feb 2014 18:00:00 GMT" */
timestamp += (((4*24+13)*60+49)*60+6)*1000;
console.log(new Date(timestamp).toUTCString());
/* Outputs "Sun, 09 Feb 2014 07:49:06 GMT" */
Try
var date = $('#inline_datepicker').datepicker("getDate");
//24 hour clock
date.setHours(14, 30);
console.log(date)
Demo: Fiddle
To get the time in milliseconds use date.getTime()

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 calculate the time difference?

How can i do the calculation to get the time difference. I have both the time of the server and the time of the client system in isoDate date format. Here are the output data i have :
Server time which is in UTC converted to local sytem timezone time :
Tue May 22 2012 14:29:51 GMT+0530 (India Standard Time)
Local System Time :
Tue May 22 2012 14:31:51 GMT+0530 (India Standard Time)
I want to do the calculation in such a way that if the local system time is less then or greater then say 5 min (configurable value) ignoring the difference in seconds compared to what the server time is showing want to perform some task else another task. I dont know how to do the calculation because when it is midnight 12:01 am according to the server time then the date, hour and minute changes whereas if the local system is just 4 min behind how to determine the difference is not less then 5 min although the date changed. My main idea is to check everything to match date, time and check the difference. Please help.
function getDateDiff(date1, date2) {
var second = 1000,
minute = second * 60,
date1 = new Date(date1).getTime();
date2 = (date2 == 'now') ? new Date().getTime() : new Date(date2).getTime(); // now means current date
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
return Math.floor(timediff / minute);
}
Use:
getDateDiff(YOUR_SERVER_DATE, YOUR_CLIENT_DATE); // output will be in unit minute
or
getDateDiff(YOUR_SERVER_DATE, 'now'); // for current date

Categories