Using getTime in a For loop in google sheets script - datetime

I am trying to run a 'for' loop that looks like this:
function runMultipleDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
//9/26/2018 is 1569477600000 and 2/28/2019 is 1551337200000; 9/21/2018 is 1537509600000
for (var date1 = 1537596000000 /*9/21/2018*/; date1 < 1569477600000 /*9/26/2018*/; date1 +=86400000) {
//runEverything();
var date2 = new Date();
date2 = date2.setTime(date1);
ss.getSheetByName('Time Range').getRange("A3").setValue(date2);
};
};
My goal is to run a function called "runEverything()" that reference a date located in cell A3 of a sheet called 'Time Range'. As long as the date in cell A3 is less that 9/26/2018, the for loop should run my function 'runEverything' and then set a new date in A3. When I do my test loop, the setValue(date2) returns a numeric value rather than a date in that cell (A3). Can someone point out how I can return the date format rather than the numeric value of date? if there is a more elegant way to achieve this, I am all ears!
Thank you for your insight!

You want to use the date string instead of the unix time
If my understanding is correct, how about the following script? Please think of this as just one of several possible answers.
Sample script:
function runMultipleDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var start = new Date("2018-09-29"); // <--- 1538200800000
var end = new Date("2018-10-05"); // <--- 1538719200000
var step = 1; // 1 day (86400000)
for (var date1 = start; date1 <= end; date1.setDate(date1.getDate() + step)) {
runEverything();
var date2 = new Date(date1.getTime());
date2.setDate(date2.getDate() + 1);
ss.getSheetByName('Time Range').getRange("A3").setValue(date2);
};
}
This script brings the same result with the script of your answer.
When the script is run, 10/06/2018 is put to the cell "A3".
References:
getDate()
setDate()

Tanaike suggested using new Date(date2) in the setValue() and it worked. My final script is something like this:
function runMultipleDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
for (var date1 = 1538200800000 ; date1 <= 1538719200000; date1 +=86400000) {
runEverything();
var date2 = new Date();
date2 = date2.setTime(date1+86400000);
ss.getSheetByName('Time Range').getRange("A3").setValue(new Date(date2));
};

Related

How to use for loop to create multiple dates?

I have a function here that gets the date, and adds one week to it:
func thingy() {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
print(futureDate!.formatted())
}
This gets the current date, adds one week to it, and prints out that date.
I want to get a for loop that will give the date, for example maybe 10 weeks in the future, maybe looking something like this:
for i in 1...num[ex: 11] {
let currentDate = Date()
var dateComponent = DateComponents()
dateComponent.day = 7
let futureDate = Calendar.current.date(byAdding: (dateComponent*i), to: currentDate)
let match = (title: "Test", date: futureDate)
}
I get this error:
Referencing operator function '*' on 'DurationProtocol' requires that 'DateComponents' conform to 'DurationProtocol'
How do I fix this?
I would advise adding .weekOfYear to the date. E.g., to get an array of Date representing the next ten weeks:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dates = (1 ... 10)
.compactMap { calendar.date(byAdding: .weekOfYear, value: $0, to: today) }

Working with Date, Time in Google Apps Script

I need help with some quick coding with google apps script, linking to my googlesheets spreadsheet.
In the googlespreadsheets, I have a cell with the value “26-Jun-2020”. It is a date.
I want to use google apps script to calculate the number of days difference between that date (“26-Jun-2020”) and today’s day, but it won’t do the calculation for me somehow.
If I print only “expiry_date[i]” using Logger.log(expiry_date[i]), it will provide the output “Fri Dec 17 2021 01:00:00 GMT-0500 (Eastern Standard Time) “
function Put_Options_Expiry_Alert() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Long equity (sell puts)");
//var timeZone = AdsApp.currentAccount().getTimeZone(); //Get timezone of current spreadsheet
var status = sheet.getRange("F:F").getValues();
var expiry_date = sheet.getRange("M:M").getValues();
var potential_capitaloutlay_USD = sheet.getRange("Z:Z").getValues();
Logger.log("Length of status = " + status.length);
Logger.log("Length of expiry_date = " + expiry_date.length);
Logger.log("Length of potential_capitaloutlay_USD = " + potential_capitaloutlay_USD.length);
for (var i = 0; i < status.length; i++) {
if (status[i] == "Entered") { //Evaluate if this is a live Put position
//Calculate the time difference of two dates using date2. getTime() – date1. getTime();
//Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24)
Logger.log("expiry date is = "+expiry_date[i]);
Logger.log("today's date is = "+Date());
var days_to_expiry = dateDiffInDays(expiry_date[i],Date());
Logger.log(days_to_expiry);
}
}
}
// Function that returns the number of days difference between DateA and DateB
// DateA and DateB are javascript Date objects
function dateDiffInDays(DateA, DateB) {
var milliseconds_per_day = 1000 * 24 * 60; // number of milliseconds in a day
const utcA = Date.UTC(2021, DateA.getMonth(), DateA.getDate());
const utcB = Date.UTC(2020, DateB.getMonth(), DateB.getDate());
return Math.floor((utc2 - utc1) / milliseconds_per_day);
}
function timeDiffDays(Start, End) {
var day = 86400000;
var t1 = new Date(Start).valueOf();
var t2 = new Date(End).valueOf();
var d = t2 - t1;
return Math.floor(d / day);
}

How to find difference between two times in 24 hour format - Flutter?

I have to find the difference between two times in 24 hour format. I have the two time strings, Eg: 10:40 and 18:20. How can I find the difference between these two times in Flutter?
You can use intl package.
var format = DateFormat("HH:mm");
var one = format.parse("10:40");
var two = format.parse("18:20");
print("${two.difference(one)}"); // prints 7:40
A complete answer for perfect calculation is given bellow
String start_time = formateTime('12:00'); // or if '24:00'
String end_time = formateTime('24:00'); // or if '12:00
var format = DateFormat("HH:mm");
var start = format.parse(start_time);
var end = format.parse(end_time);
if (start.isAfter(end)) {
print('start is big');
print('difference = ${start.difference(end)}');
} else if(start.isBefore(end)){
print('end is big');
print('difference = ${end.difference(start)}');
}else{
print('difference = ${end.difference(start)}');
}

Javascript Moment.js add a day to a date in milliseconds

I am trying to add a day to a date in milliseconds.
The code I am using is bellow.
var x = 1450612800000;
var timeFrame = 'days'
x = moment(x).add(timeFrame, 1);
console.log(x['_i']) //returns 1450612800000
Here is the fix:
var x = 1450612800000;
var timeFrame = 'd'
var newDay = moment(x).add(tf, 1);
console.log('newDay');
//Get New Date in Milliseconds format
console.log(newDay.valueOf());
//Get New Date in Date Format
console.log(newDay.toDate());
Take a look at this StackOverflow answer: https://stackoverflow.com/a/28132227/3692354
_i isn't what you want to use here - that's the input that was used to create the moment object. I think what you want to use instead is moment's valueOf function: http://momentjs.com/docs/#/displaying/unix-offset/

Getting date as string - need to convert

Programming in Flex 4.5
I'm getting a date as a String.
I don't know what date or hour I'm getting.
I want to convert the string to date and take only the hours & minutes.
For example:
Getting - "2012-02-07T13:35:46+02:00"
I want to see: 13:35.
Suggestions or any other solutions?
After some digging, Solution:
var myDate:Date;
myDate = DateFormmater.parseDateString(myDateString);
var dateResult:String = myDate.getHours() + ":" + myDate.getMinutes();
Thanks anyway! :-)!
You can to use date.getHours() and date.getMinutes(). Try the following:
var d:Date = DateField.stringToDate("your_date_string","YYYY-MM-DD");
trace("hours: ", date.getHours()); // returns 13
trace("minutes: ", date.getMinutes()); // returns 35
private function init():void
{
var isoStr:String = "2012-02-07T13:35:46+02:00";
var d:Date = new Date;
d = isoToDate(isoStr)
trace(d.hours);
}
private function isoToDate(value:String):Date
{
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("+02:00", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I see you've already got the answer, but for future users, here it is.
var myDateString:String="2012-02-07T13:35:46+02:00"
//This is of the format <yyyy-mm-dd>T<hh:mm:ss><UTC-OFFSET AS hh:mm>
//You could write your own function to parse it, or use Flex's DateFormatter class
var myDate:Date=DateFormatter.parseDateString(myDateString);
//Now, myDate has the date as a Flex Date type.
//You can use the various date functions. In this case,
trace(myDate.getHours()); //Traces the hh value
trace(myDate.getMinutes()); //Traces the mm value

Resources