js different variable same value - javascript

Currently i'm facing the following problem. In my JavaScript code, i have a function, which should calculate the weeks from now, to a given timestamp. The problem is, that the the first value has the same Value as another variable with another name. The code:
let myAppointment = event.data.toTime;
console.log(myAppointment);
let currentDate = new Date(Date.now());
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
let appointmentStartDate = new Date(myAppointment.getStart());
console.log(appointmentStartDate);
console.log(currentDate);
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
console.log('AppointmentStartTime : ' + appointmentStartTime);
console.log('CurrentTime: ' + currentTime);
let timeskip = appointmentStartTime - currentTime;
console.log(timeskip + ' timeskip / 604800000 = ' + (timeskip / 604800000));
skips = timeskip / 604800000;
await displayCalendar(document.getElementById('wrapper'));
console.log(skips);
if(skips < 0){
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateBackward(skips);
}
}else{
skips = Math.floor(skips);
if(Math.abs(skips) != 1){
navigateForward(skips);
}
}
cleanTable();
displayAppointments();
});
//i think this function may be interesting too, but the error can't occur from here
function
convertStringDateToDate(year,month,day,hours,minutes,seconds,milliseconds){
let date = new Date();
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(seconds);
date.setMilliseconds(milliseconds);
return date;
}
The function from let myAppointment = ... Leads to the following console output

The problem lies here:
let appointmentStartTime = (convertStringDateToDate(appointmentStartDate.getFullYear(), appointmentStartDate.getMonth(), appointmentStartDate.getDate(),0,0,0,0)).getTime();
You set the hours, minutes, seconds all to zero - effectively turning your start date to the same value as today's date.

Note that in your particular example, currentDate and appointmentStartDate share the same year, month, and date. When you call let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0,0,0,0)).getTime();
, you should replace 0,0,0,0 with correct values for both currentTime and appointStartTime.
To make your coding style consistent, you can use date.getHours(), date.getMinutes(), date.getSeconds(), and date.getMilliseconds() to replace those four zeroes.
Also, if you want to shorten your code, you can get rid of convertStringDateToDate() and merely call getTime() on currentDate and appointStartDate.
let currentDate = new Date();
let currentTime = (convertStringDateToDate(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds(),currentDate.getMilliseconds())).getTime();
console.log(currentTime); // 1537309553647
console.log(currentDate.getTime()); // 1537309553647

Related

Google App Scripts - Getting a constant "Yesterday"

I'm trying to set a const "Yesterday" but the script is not recognised as a function (I'm using Google App Scripts).
I've tried different syntax including:
const yesterday = today.setDate(-1);
and
const yesterday = new Date(today.setDate(-1));
But neither worked.
I'm pretty sure it should be a minor change but I cannot figure out how to solve this.
A little help would be highly appreciated, thanks !
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('My Report');
function insertColumn() {
const range = sheet.getRange('H1:H69').getValues();
const newrange = sheet.getRange('I1:I69');
const rules = sheet.getConditionalFormatRules();
const today = Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy");
const yesterday = new Date(today.setDate(-1));
Your issue is that today is not a Date object, because you've called Utilities.formatDate on it. This is why you are getting an error when trying to use today.setDate(). So you need to use another variable to allow you to compute yesterday. For example:
const tmp = new Date();
const yesterday = new Date(tmp.setDate(tmp.getDate()-1))
Also note that setDate(-1) sets the date to the penultimate day in the previous month (e.g. March 30 when you are in April), you need to get the current date (using getDate) and subtract 1 from that to get yesterday's date.
getYesterday() {
let date = new Date();
let yesterday_milliseconds = date.getTime() - 1000 * 60 * 60 * 24;
let yesterday = new Date();
yesterday.setTime(yesterday_milliseconds);
let strYear = yesterday.getFullYear();
let strDay = yesterday.getDate();
let strMonth = yesterday.getMonth() + 1;
if (strMonth < 10) {
strMonth = "0" + strMonth;
}
if (strDay < 10) {
strDay = "0" + strDay;
}
return strYear + "-" + strMonth + "-" + strDay;
},
function yesterday() {
let dt = new Date();
Logger.log(new Date(dt.setDate(dt.getDate() - 1)));
}
From MDN setDate() returns: The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date... not a date object

create date object by hours and minutes

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')
var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN
You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);
It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

take a date string, add a class to span if expiration date is less than 2 weeks from now

i've been stuck on this problem for a while now and I am ready to pull my hair out :). I have to add a class to a span if a campaign date is expiring in 2 weeks or less. The date retrieved is a string in the following format
07/26/2017
when I run this function, I am passing the datestring as an argument since the method will be attached to the var which holds the string. But for whatever reason this logic isn't working. Am I totally screwing this up? It's failing silently somewhere. Thank you. I know it should be easy but I am caught in a loop.
campMethods.EndDateAlert = function (dateString) {
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14)
var $EndDateSpan = $('.campaign-end-date');
if (dateString <= twoWeeks) {
$EndDateSpan.addClass('red');
}
return dateString;
};
You can do that with some Math. The key is, 2 weeks = 14 days.
Here is Pure Javascript example for you:
var date = "07/26/2017".split("/");
var formatedDate = (date[2] + '' + date[0] + '' + date[1]);
var currentDate = new Date();
var today = currentDate.getFullYear() +''+ ("0" + (currentDate.getMonth() + 1)).slice(-2)+''+("0" + currentDate.getDate()).slice(-2);
var compareDay = formatedDate - today;
if(compareDay < 14){// 14 day = 2 week
// do something for less than 2 weeks
console.log('Less than 2 weeks will be expired');
} else {
// also can do something
console.log('more than 2 weeks will be expired.');
}
Javascript Date Reference
Try comparing milliseconds of the dates.
We know that there are 1000 * 60 * 60 * 24 * 14 = 1209600000 milliseconds in two weeks, knowing this we can add 1209600000ms to the current date and compare this to the milliseconds of the due date.
let dueDate = new Date('07/26/2017');
if(Date.now() + 1209600000 > dueDate.getMilliseconds()){
//do stuff
}

TypeError: *.getMonth is not a function

I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:
function filldates() {
datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}
However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"
Is this an implementation problem?
The setDate() function mutates its context date. It does not return a new Date instance.
If you want to create a new date instance that's some number of days ahead of another one:
function daysAfter(d, days) {
var nd = new Date(d.getTime());
nd.setDate(d.getDate() + days);
return nd;
}
Then if you've got a date, you can create a date 14 days after it like this:
var someDate = ... whatever ... ;
var fourteenDaysAfter = daysAfter(someDate, 14);
You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.
edit for dates before a date just pass a negative number.

Categories

Resources