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);
}
I'm looking for a way to use DateTime to parse two dates, to show the difference.
I want to have it on the format: "X years, Y months, Z days".
For JS, we have momentjs library and following code::
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'year');
b.add(years, 'years');
var months = a.diff(b, 'months');
b.add(months, 'months');
var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days
Is there similar library available for dart that can help achieve this usecase?
I think it is not possible to do exactly what you want easily with DateTime. Therefore you can use https://pub.dev/packages/time_machine package that is quite powerful with date time handling:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDate a = LocalDate.today();
LocalDate b = LocalDate.dateTime(DateTime(2022, 1, 2));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}");
}
for hours/minutes/seconds precision:
import 'package:time_machine/time_machine.dart';
void main() {
LocalDateTime a = LocalDateTime.now();
LocalDateTime b = LocalDateTime.dateTime(DateTime(2022, 1, 2, 10, 15, 47));
Period diff = b.periodSince(a);
print("years: ${diff.years}; months: ${diff.months}; days: ${diff.days}; hours: ${diff.hours}; minutes: ${diff.minutes}; seconds: ${diff.seconds}");
}
What you are looking for is the Dart DateTime class
You can get close to what you want in moment.js with
main() {
var a = DateTime.utc(2015, 11, 29);
var b = DateTime.utc(2007, 06, 27);
var years = a.difference(b);
print(years.inDays ~/365);
}
There is no inYears or inMonths option for DateTime though that's why the year is divided in the print.
the difference function returns the difference in seconds so you have to process it yourself to days.
You could write an extension on duration class to format it:
extension DurationExtensions on Duration {
String toYearsMonthsDaysString() {
final years = this.inDays ~/ 365
// You will need a custom logic for the months part, since not every month has 30 days
final months = (this.inDays ~% 365) ~/ 30
final days = (this.inDays ~% 365) ~% 30
return "$years years $months months $days days";
}
}
The usage will be:
final date1 = DateTime()
final date2 = DateTime()
date1.difference(date2).toYearsMonthsDaysString()
You can use Jiffy Package for this like this
var jiffy1 = Jiffy("2008-10", "yyyy-MM");
var jiffy2 = Jiffy("2007-1", "yyyy-MM");
jiff1.diff(jiffy2, Units.YEAR); // 1
jiff1.diff(jiffy2, Units.YEAR, true);
You can calculate from the total number of days:
void main() {
DateTime a = DateTime(2015, 11, 29);
DateTime b = DateTime(2007, 06, 27);
int totalDays = a.difference(b).inDays;
int years = totalDays ~/ 365;
int months = (totalDays-years*365) ~/ 30;
int days = totalDays-years*365-months*30;
print("$years $months $days $totalDays");
}
Result is: 8 5 7 3077
I created my own class for Gregorian Dates, and I created a method which handle this issue, it calculates "logically" the difference between two dates in years, months, and days...
i actually created the class from scratch without using any other packages (including DateTime package) but here I used DateTime package to illustrate how this method works.. until now it works fine for me...
method to determine if it's a leap year or no:
static bool leapYear(DateTime date) {
if(date.year%4 == 0) {
if(date.year%100 == 0){
return date.year%400 == 0;
}
return true;
}
return false;
}
this is the method which calculates the difference between two dates in years, months, and days. it puts the result in a list of integers:
static List<int> differenceInYearsMonthsDays(DateTime dt1, DateTime dt2) {
List<int> simpleYear = [31,28,31,30,31,30,31,31,30,31,30,31];
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
int totalMonthsDifference = ((dt2.year*12) + (dt2.month - 1)) - ((dt1.year*12) + (dt1.month - 1));
int years = (totalMonthsDifference/12).floor();
int months = totalMonthsDifference%12;
late int days;
if(dt2.day >= dt1.day) {days = dt2.day - dt1.day;}
else {
int monthDays = dt2.month == 3
? (leapYear(dt2)? 29: 28)
: (dt2.month - 2 == -1? simpleYear[11]: simpleYear[dt2.month - 2]);
int day = dt1.day;
if(day > monthDays) day = monthDays;
days = monthDays - (day - dt2.day);
months--;
}
if(months < 0) {
months = 11;
years--;
}
return [years, months, days];
}
the method which calculates the difference between two dates in months, and days:
static List<int> differenceInMonths(DateTime dt1, DateTime dt2){
List<int> inYears = differenceInYearsMonthsDays(dt1, dt2);
int difMonths = (inYears[0]*12) + inYears[1];
return [difMonths, inYears[2]];
}
the method which calculates the difference between two dates in days:
static int differenceInDays(DateTime dt1, DateTime dt2) {
if(dt1.isAfter(dt2)) {
DateTime temp = dt1;
dt1 = dt2;
dt2 = temp;
}
return dt2.difference(dt1).inDays;
}
usage example:
void main() {
DateTime date1 = DateTime(2005, 10, 3);
DateTime date2 = DateTime(2022, 1, 12);
List<int> diffYMD = GregorianDate.differenceInYearsMonthsDays(date1, date2);
List<int> diffMD = GregorianDate.differenceInMonths(date1, date2);
int diffD = GregorianDate.differenceInDays(date1, date2);
print("The difference in years, months and days: ${diffYMD[0]} years, ${diffYMD[1]} months, and ${diffYMD[2]} days.");
print("The difference in months and days: ${diffMD[0]} months, and ${diffMD[1]} days.");
print("The difference in days: $diffD days.");
}
output:
The difference in years, months and days: 16 years, 3 months, and 9 days.
The difference in months and days: 195 months, and 9 days.
The difference in days: 5945 days.
the answer is yes, you can easilly achieve it with DateTime class in Dart. See: https://api.dart.dev/stable/2.8.3/dart-core/DateTime-class.html
Example
void main() {
var moonLanding = DateTime(1969,07,20)
var marsLanding = DateTime(2024,06,10);
var diff = moonLanding.difference(marsLanding);
print(diff.inDays.abs());
print(diff.inMinutes.abs());
print(diff.inHours.abs());
}
outputs:
20049
28870560
481176
final firstDate = DateTime.now();
final secondDate = DateTime(firstDate.year, firstDate.month - 20);
final yearsDifference = firstDate.year - secondDate.year;
final monthsDifference = (firstDate.year - secondDate.year) * 12 +
firstDate.month - secondDate.month;
final totalDays = firstDate.difference(secondDate).inDays;
Simple approach, no packages needed.
try intl package with the following code:
import 'package:intl/intl.dart';
String startDate = '01/01/2021';
String endDate = '01/01/2022';
final start = DateFormat('dd/MM/yyyy').parse(startDate);
final end = DateFormat('dd/MM/yyyy').parse(endDate);
Then, you can calculate the duration between the two dates with the following code:
final duration = end.difference(start);
To obtain the number of years, months and days, you can do the following:
final years = duration.inDays / 365;
final months = duration.inDays % 365 / 30;
final days = duration.inDays % 365 % 30;
Finally, you can use these variables to display the result in the desired format:
final result = '${years.toInt()} years ${months.toInt()} months y ${days.toInt()} days';
DateTime difference in years is a specific function, like this:
static int getDateDiffInYear(DateTime dateFrom, DateTime dateTo) {
int sign = 1;
if (dateFrom.isAfter(dateTo)) {
DateTime temp = dateFrom;
dateFrom = dateTo;
dateTo = temp;
sign = -1;
}
int years = dateTo.year - dateFrom.year;
int months = dateTo.month - dateFrom.month;
if (months < 0) {
years--;
} else {
int days = dateTo.day - dateFrom.day;
if (days < 0) {
years--;
}
}
return years * sign;
}
difHour = someDateTime.difference(DateTime.now()).inHours;
difMin = (someDateTime.difference(DateTime.now()).inMinutes)-(difHour*60);
and same for years and days
I am trying to get date range for a particular week number.
Following is my code to get week number with respect to current date
final date = DateTime.now();
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();
if (daysInFirstWeek > 3) {
weeks += 1;
}
print("Week Range $weeks");
What I don't understand is how I get start and end date for a particular week number.
Any help would be appreciated.
Assuming your week is zero based, you need to do something like this:
final date = new DateTime.now();
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();
main(){
int week = weeks;
print("Start Date for week $week: ${startOfYear.add(Duration(days: 7*week))}");
print("End Date for week $week: ${startOfYear.add(Duration(days: 7*week+6))}");
}
To get the starting and day of week from week number and year.
DateTime getDateByWeekNumber({
int weeknumber,
int year,
bool start
}) {
//check if start == true retrun start date of week
//else return end date
var days = ((weeknumber - 1) * 7) + (start ? 0 : 6);
return DateTime.utc(year, 1, days);
}
This is in accordance to ISO 8601. You can very week number here
I would like to subtract days from the current date in TypeScript.
For example, if the current date is October 1st, 2017, I would like to subtract 1 day to get September 30th, 2017, or if I want to subtract 3 days I would get September 28th etc.
This is what I have so far, the result is I received December 31st, 1969. Which I assume means that tempDate.getDate() is returning zero, as in the Epoch of January 1, 1970.
This is my code, the goal is to return the previous working day.
protected generateLastWorkingDay(): Date {
var tempDate = new Date(Date.now());
var day = tempDate.getDay();
//** if Monday, return Friday
if (day == 1) {
tempDate = new Date(tempDate.getDate() - 3);
} else if (1 < day && day <= 6) {
tempDate = new Date(tempDate.getDate() - 1);
}
return tempDate;
}
getDate returns the date of the month (1-31), so creating a new Date from it treats that number as "milliseconds since epoch".
What you probably want is to use setDate to change the date as it automatically handled going backwards through months/years.
protected generateLastWorkingDay(): Date {
const lastWorkingDay = new Date();
while(!this.isWorkingDay(lastWorkingDay)) {
lastWorkingDay.setDate(lastWorkingDay.getDate()-1);
}
return lastWorkingDay;
}
private isWorkingDay(date: Date) {
const day = date.getDay();
const isWeekday = (day > 0 && day < 6);
return isWeekday; // && !isPublicHoliday?
}
This is how I did
let yesterday=new Date(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
let last3days=new Date(new Date().getTime() - (3 * 24 * 60 * 60 * 1000));
We need to minus (no_of_days) * 24 * 60 * 60 * 1000 from current date.
You can just
const current = new Date()
and then
const numberOfDaysToSubstract= 3;
const prior = new Date().setDate(current.getDate) - numberOfDaysToSubstract);
you can see an example of this here
https://codepen.io/Jeysoon/pen/poNZRwd?editors=1112
I want to make a js function. When I input year and month number, if there is a black friday in that month, it will returns true.
Is there any simlar moment.js method or function to do this? Thx.
You can create a moment object representing the 13th of the given month using using moment({unit: value, ...}); then you can get day of week using day(). As docs says:
This method can be used to set the day of the week, with Sunday as 0 and Saturday as 6.
so you can check if day() is equal to 5 (Friday).
Here a working example:
function hasBlackFriday(year, month) {
return (moment({y: year, M: month, d: 13}).day() === 5);
}
// Test foreach month of 2017
for(var i=0; i<12; i++){
console.log(hasBlackFriday(2017, i));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Keep in mind that, as moment({unit: value, ...}); docs says:
Note that like moment(Array) and new Date(year, month, date), months are 0 indexed.
As Matt Johnson highlighted in the comments, you can get the same result also using native JavaScript Date object, here a sample:
function hasBlackFriday(year, month) {
return (new Date(year, month, 13).getDay() === 5);
}
// Test foreach month of 2017
for(var i=0; i<12; i++){
console.log(hasBlackFriday(2017, i));
}
This function returns the date for last Friday of the given month m and year y.
function hasBlackFriday(y, m) {
var date = moment(new Date(y, m - 1, '1'))
result = date.endOf('month');
while (result.day() !== 5) {
result.subtract(1, 'day');
}
return result;
}
console.log(hasBlackFriday(2017, 4).format('M DD YY'))