I want to write a JavaScript to compare today's date with one field in a MsSql database assuming that the field name is "document_issuedate" and put this condition.
if today's date - document_issuedate > 30 then alert
How to calculate date difference in javascript
This question is similar, and appeared after a quick search. Basically, as long as you make the dates into a date object you can simply just subtract them like you've shown
Edit
Here's a better link then with more explanations and the appropriate snippet from that page.
The oneDay variable is just there for convenience.
The date objects are in Y,m,d format.
Using getTime() on the date objects makes it so the difference gives a numeric value (in milliseconds) instead of a date object. Then dividing it by oneDay converts the milliseconds into days which is what you want. Math.abs makes sure you always have a positive number difference and Math.round makes it a whole number instead of a decimal
How to calculate the number of days between two dates using JavaScript?
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
Related
I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.
I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);
I'm currently just practising JavaScript and I'm trying to create a programme that calculates how many days there are until your next birthday.
I have seen on this site that there is a daysBetween function that I can use to tell the time difference between two dates (I just need to turn these dates into the millisecond value since the 1st Jan 1970).
The problem is that, although one of those dates is the current date (which is easy to convert into its millisecond value), the second is derived from answers the user inputs as a string into a prompt command (there are three different boxes that ask for the year, month and date of their birth). Is there a way I can convert these input strings into a date format that I can then use to find the days between today's date and their next birthday?
Thanks and sorry if this is a stupid question!
Remember in JS that months are indexed from 0, so January === 0.
var date = new Date('2017','5','25'); would be today, assume you have something like:
var userDd = '25';
var userMm = '6'; // User doesn't know the months are indexed at 0.
var userYy = '2017';
var date = new Date(userYy, userMm - 1, userYy);
date.getTime(); // returns the milliseconds value.
Am trying to get number of hours between two time objects. Am using 24h time format. If the difference in hours is higler than 24 hours, I want to increase price for some cars.
User can select start time and end time from input typte=time: 10:25 / 23:45
Which is the best approach to do this. I google but that examples i dont understand clearly...
Just subtract them if they are date objects, if they are not make them.
You can get the amount of hours between two dates with:
var date1 = new Date('2016,03,10');
var date2 = new Date();
var hoursBetween = ((date1-date2)/1000)/3600;
Why is the below code actually working?
Code
var firstDate = new Date();
// some time passing here
var secondDate = new Date();
// Difference seems to contain difference in miliseconds.
var difference = secondDate - firstDate;
What I get is, I believe, an equivalent to secondDate.getTime() - firstDate.getTime(). The only question is, how can this conversion to number of milliseconds happen in background? Is this some sort of operator-overloading?
The operator - converts the operands to numbers (check for example "12"-3). The date object defines a numeric conversion .valueOf() that returns the number of milliseconds.
See also for example +(new Date).