Google spreadsheet script to calculate the last weekday - javascript

I've a Google sheets script where I try to find yesterday's date as a workday by subtracting 1 from today's date.
//Get today's date
var today = new Date();
//Take today's date and subtract 1 making yesterday's date
var yesterday = new Date(today.getTime()-1 * (24*3600*1000));
The problem I face is that on a Monday it will return a Sunday, rather than a Friday.
I tried to use the Workday function to fix the issue but I am getting some not defined errors.
var yesterday = new Date(WEEKDAY((today.getTime()-1 * (24*3600*1000)));
What would be the best method for fixing the issue?

Related

JS how to get month, week, past 3 days from today

In js how can I get the timestamp of a date like 2 weeks ago. For example I get the current timestamp, Then I need to get the timestamp 3 days ago, or 2 weeks ago, or a month ago. Is there a moment library that does this? I cant find anything online.
As the comments say, check out Moment JS: https://momentjs.com/
moment().subtract(10, 'days').calendar(); // 02/11/2021
moment().subtract(6, 'days').calendar(); // Last Monday at 12:17 AM
moment().subtract(3, 'days').calendar(); // Last Thursday at 12:17 AM
moment().subtract(1, 'days').calendar(); // Yesterday at 12:17 AM
moment().calendar(); // Today at 12:17 AM
moment().add(1, 'days').calendar(); // Tomorrow at 12:17 AM
moment().add(3, 'days').calendar(); // Wednesday at 12:17 AM
moment().add(10, 'days').calendar();
moment().format(); // 2021-02-21T00:43:34-08:00
Try:
moment().subtract(6, 'days').format()
Handling date objects in javascript is bit tricky compared to other general purpose languages. However this could be achieved in Java script's Date.parse(date) method.
This method returns the timespan between the given date and 1970-01-01 in milliseconds.
So, I would do something like below to manipulate your scenario.
function getNewDate(originalDate, dateOffset){
// converting original date to milliseconds
var originalMS = Date.parse(originalDate);
// calculating your date offest in milliseconds
var offsetMS = dateOffset * 1000 * 3600 * 24;
// apply the offset millisecons to original moment
var newDateMS = originalMS + offsetMS;
// Convert it back to new date object and return it
return new Date(newDateMS);
}
You need to pass a date object and desired timespan in days as parameters to this function.
So you would call it as follows
var originalDate = new Date();
// To get new date after 2 weeks for the given original date
getNewDate(originalDate, 14)
// To get new date before 2 weeks for the given original date
getNewDate(originalDate, -14)
I hope this would answer you problem.

Get Date from googlesheets and create a counter in javascripts that counts days past

Is it possible to get value from a Google Sheets cell that contains a Date and count on another cell how many days have past since that date in JavaScript?
The problem is that when you are coding in JavaScript it is not easy to do numeric calculations with dates that you get from cells. So if I do the following it does not work correctly
function myFunction() {
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var start_date=ss.getRange(2,14).getValue()
var today=new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate())
var difference=today-start_date
ss.getRange(2,14).setValue(difference)
}
The date at the targeted cell is 4/12/2019
and The result that I get is 3786824092000
Assuming your code to read/write in Google sheet is correct. Below code should work for you.
var start_date = new Date(ss.getRange(2,14).getValue());
var today=new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate())
var difference= (today-start_date) / 86400000;
ss.getRange(2,14).setValue(difference)

Incorrect time shown in Google LineChart

There are dates stored as timestamp in the MySQL database. If I view them with phpMyAdmin the correct time is shown. In a php script I try to output the date with UNIX_TIMESTAMP into a Javascript Date Object (new Date()). When displaying the data in a Google Chart there is a time offset of +2:00 hours (my current timezone). I also looked into the timestamp and a timestamp converter told me that the local time is correct and UTC time is -2:00 hours.
In the php-script I already set the timezone with date_default_timezone_set(). SELECT ##global.time_zone, ##session.time_zone; outputs SYSTEM. But I still get the time offset. Now I use
SELECT UNIX_TIMESTAMP(CONVERT_TZ(Timestamp, "+02:00", ##session.time_zone)) ...
and I get the correct data. Does this mean that the data is stored with a 2 hours offset? Why does phpMyAdmin showing me the correct date and time? Or does the Google chart expects UTC time and the browser automatically adds the difference for the timezone?
What is the real problem here?
Now I wrote a function which converts the timestamp from the database into an UTC date:
function getDateinUTC(timestamp){
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we'll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
return new Date(year, month, day, hours, minutes, seconds);
}
When I create the DataTable I simply call the function as shown here:
rows: [
{c:[{v:getDateinUTC(stamp)}, {v: value}]},
]
You have to replace stamp and value with your php-code which fills the place.
This idea is based on the article Automatic timezone conversion in JavaScript by David Mytton.
So far the times seems to be correct.

javascript: fetch day of the week based on a specific date

I searched stackoverflow but did not find a solution to my problem.
I have a specific date say 2014-05-20 and I want to get the Day of the week for the mentioned date.
I tried the following
var date = new Date();
console.log(date.getDay());
But this return the Current Day. What I require is the day based on the given date!
I also tried
var givendate = '2014-05-20';
new Date(givendate)
But the above does not generate anything.
Your question both code you combine and check answer is get on yourself without my answer still i show you code,
Check this Demo jsFiddle
JavaScript
var givendate = '2014-05-20';
var date = new Date(givendate);
console.log(date.getDay());
Console log
2
you may try
var date = new Date(2014, 05, 20).getDay(); // Date(year, month, date)
console.log(date);
you will get integer 0 for sunday - 6 for saturday

JavaScript date math not working

I have searched this forum and found many useful answers, but one of the answers that I used only works under certain conditions.
I am populating a week calendar, and simply need to determine the start of the week (Monday) from a Date picker, and then I add to that date to populate text fields with the following 6 days. This works only if the date picker selection is in the same month.
So, if I select Wednesday May 15th 2013, it correctly returns and populates the Monday with May 13, the Tuesday with May 14, etc.
But, if I select Wednesday May 1, 2013, it correctly populates Monday Apr 29, but Tuesday it puts as May 30 (adding a month instead of a day).
I should note that I am building this in Application Craft, so I don't know if that has any impact.
Here's my code:
var curr = new Date(app.getValue("DatePicker2")); // get selected date
var first = curr.getDate() - curr.getDay() +1; // Adjust for monday start of week
var firstday = new Date(curr.setDate(first));
var secondday = new Date();
secondday.setDate(firstday.getDate()+1);
Can anyone see where I have gone wrong?
Thanks
Tammy
Here
secondday.setDate(firstday.getDate()+1)
since you are specifying only the date in the setDate function, it would assume "this" month which happens to be May in this case
So, you can do
secondday = new Date(firstday.getFullYear(), firstday.getMonth(), firstday.getDate()+1)

Categories