Trouble subtracting day from date in Sheets Script - javascript

I have written the following code and cannot figure out why it is not working in my Google Sheet:
function WEEKOF(myDay, myDate) {
var wkDate = new Date(myDate);
var StartDate = new Date();
StartDate.setDate(wkDate.getDate()-myDay);
return StartDate;
}
=WEEKOF(Weekday(A1), A1)
Cell A1 contains: 05/01/2016
Return: 7/26/2017
I'm expecting the return to be: 04/29/2016

Difference in Days,Hours,Minutes and Seconds
var adayinmilliseconds=24*60*60*1000;
var differenceBetweenTwoDatesInDays = Math.floor((date1.valueOf()-date2.valueOf())/adayinmilliseconds);
A Date Difference Function that output days, hours, minute and seconds. From the MDN Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC. The method of time() and valuOf() both provide us the the primitive value of dates ie the number of milliseconds from some date in the past. Yes, it can be quite a large number but in the end with a little simple arithmetic Math.floor(), /, % you end up with an easy calculation. You can change the output to an array or an object depending upon your requirements.
function calcTimeDifference(Start,End)
{
if(Start && End)
{
var second=1000;
var minute=60*second;
var hour=minute*60;
var day=hour*24;
var t1=new Date(Start).valueOf();
var t2=new Date(End).valueOf();
var d=t2-t1;
var days=Math.floor(d/day);
var hours=Math.floor(d%day/hour);
var minutes=Math.floor(d%day%hour/minute);
var seconds=Math.floor(d%day%hour%minute/second);
return 'dd:hh:mm:ss\n' + days + ':' + hours + ':' + minutes + ':' + seconds;
}
else
{
return 'Invalid Inputs';
}
}

Related

Get difference in months and list the months in an array between two dates in javascript

I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.

Add a variable number to a date in Java script

I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}
As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.
A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/
Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.

Date object returns NaN when trying to calculate time between two dates in IE8

I have a string which represents the expiry of an item like so: 2020-10-31T21:30:11, and I have a function to calculate the amount of days left until this date (below).
However, in IE8 it doesn't work. I think this is because timeEnd is returning NaN. Can someone explain why this doesn't work and point me in the right direction?
I have a jsFiddle here.
And here's a snippet of my code:
HTML
<span class="days-left" data-publishend="2020-10-31T21:30:11"></span>
JS
$('.days-left').each(function () {
if ($(this).data("publishend")) {
var timeEnd = new Date($(this).data("publishend")), // returns NaN in IE8
timeNow = new Date(),
oneDay = 24*60*60*1000,
oneHour = 60*60*1000,
oneMin = 60*1000,
daysLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneDay),
hoursLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneHour),
minsLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneMin),
string;
if (daysLeft < 1) {
if (hoursLeft < 1.5) {
string = minsLeft + ' minutes';
} else {
string = hoursLeft + ' hours left';
}
}
if (daysLeft === 1) string = '1 day left';
if (daysLeft > 1) string = daysLeft + ' days left';
$(this).text(string);
}
});
You are right, IE8 won't parse your date right at the beginning (timeEnd init).
Here is the reason : https://stackoverflow.com/a/17593482/2143734
Just one more date handling issue ;)
try this
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
to make the conversion.
Source: Date constructor returns NaN in IE, but works in Firefox and Chrome
From looking at answers in this Stackoverflow question, I've got a grasp of what was going on and created my own function that worked the string that I wanted to convert a date object.
IE8 cannot parse the string 2020-10-31T21:30:11 like other browsers can. But the date object can accept comma separated values representing the year, month, day, etc, and use them to create the new instance (more info about the Date object).
So I created a function that takes my string, spits it at the "T" and then splits the remaining values at either the "-" or the ":". The function then returns the a date object instance using these values as the parameters.
function parseDateString(dateString) {
var a = dateString.split('T'),
year = a[0].split('-')[0],
month = a[0].split('-')[1],
day = a[0].split('-')[2],
hour = a[1].split(':')[0],
min = a[1].split(':')[1];
return new Date(year, month - 1, day, hour, min);
}

Javascript Validate Date&Time

Ive got a piece of JS that needs to validate and compare a start date and time against an end date and time.
So in other words end date & time cannot be less than start date and time.
Now the problem.
I originally only accepted the time in 24 hour(military) Format. but now let the user choose between 12 hour or 24 hour.
Example 13:00 or 1:00 PM
This piece of code work for 24 hour time format, but not for 12, its 12:00 PM that causes the problem.
So I need to adapt this piece of code to work for either 12 hour or 24 hour, but im not sure how to do this.
function validateStartEndTime() {
var date = document.getElementById("datepickerStart").value;
var dateEnd = document.getElementById("datepickerEnd").value;
if (!isValidDate(date)) {
alert("Not Valid Date");
return false;
}
var start = document.getElementById("timepicker").value;
var end = document.getElementById("timepickerEnd").value;
var stDate = new Date(parse(date +" "+ start));
var enDate = new Date(parse(dateEnd + " "+ end));
var compDate = enDate - stDate;
if (compDate >= 0)
return true;
else {
alert("End time must be greater than Start Time ");
return false;
}
}
You could write a function that converts time in 12 hour format to time in 24 hour format, something like:
function convertTo24HourFormatIfNeeded(timeString) {
var is12HourFormat = timeString.indexOf("M") !== -1;
if (is12HourFormat) {
var isPm = timeString.indexOf("PM") !== -1;
var timeStringNoSuffix = timeString.split(" ")[0];
if (isPm) {
var hoursAndMinutes = timeStringNoSuffix.split(":");
var hours = hoursAndMinutes[0];
var convertedHours = (Number(hours) + 12);
var minutes = hoursAndMinutes[1];
return convertedHours + ":" + minutes;
} else {
return timeStringNoSuffix;
}
} else {
return timeString;
}
}
Then use it in your code:
var start = convertTo24HourFormatIfNeeded(document.getElementById("timepicker").value);
var end = convertTo24HourFormatIfNeeded(document.getElementById("timepickerEnd").value);
If you're not adverse to using external libraries, i found MomentJs to be very handy working with dates, and among other things it allows to parse the date in a user-defined format, so you could build your date string accordingly to user selection of AM/PM or 24-hour format and feed it to moment js.

Javascript DateDiff

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.
Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?
//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).
EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!
//Set the two dates
var currentTime = new Date()
var currDate = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.
//currDate = 8/17/12 and iniPastedDate = 8/7/12
function DateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value
}
//Write out the returning value should be using this example equal -10 which means
//it has passed by ten days. If its positive the date is coming +10.
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.
The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.
function setDateWeek(setDay){
var d = new Date();
d.setDate(d.getDate() - setDay); // <-- add this
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
return curr_date + "-" + curr_month + "-" + curr_year;
}
setDateWeek(1);
No need to include JQuery or any other third party library.
Specify your input date format in title tag.
HTML:
< script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">
Use javascript function:
IP_dateDiff(strDate1,strDate2,strDateFormat,debug[true/false])
alert(IP_dateDiff('11-12-2014','12-12-2014','DD-MM-YYYY',false));
IP_dateDiff function will return number of days.

Categories