Comparing dates in google app script one comparison works and one doesn't - date

I am trying to loop through some dates in a spreadsheet and come up with a date range earliest and last dates. Currently my variable lastdate works well. I can't figure out why firstdate isn't working as all that is done is I reversed the comparator (> to <) and changed variable names. The date1 variable is a date in the past month.
I have also tried this with if (date1.getTime() < firstDate.getTime()) firstDate = date1; and if (date1.toString() < firstDate.toString()) firstDate = date1;as suggested in other threads to no avail.
IAny help would be greatly appreciated! Thanks in advance!
--dwb
'''
var firstDate = new Date(2075,01,01);
firstDate = Utilities.formatDate(firstDate, "GMT-5", 'MM/dd/YYYY');
var lastDate = new Date(2000,01,01);
lastDate = Utilities.formatDate(lastDate, "GMT-5", 'MM/dd/YYYY');
tables.forEach(table => { // Selecting correct table based on cell (0,0) = "Date"
if(table.getCell(0,0).getText() == "Date"){
rows.forEach(function(row,index){
var date1 = Utilities.formatDate(row[0], "GMT-5", "MM/dd/yyyy");
// Calculating First and Last Date
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
'''

I got it working. Code is below. Note that to make it readable in the end you have to print out the date using Utilies.formatDate().
Bonus points if someone can tell me why the lastDate from the original problem worked and the firstDate did not.
Cheers,
--dwb
var date1 = new Date(row[0]).setHours(0,0,0,0);
var firstDate= new Date("01/01/2075").setHours(0,0,0,0);
var lastDate= new Date("01/01/2000").setHours(0,0,0,0);
// Calculating First and Last Date
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
//Format Date into readable format
body.replaceText('{{Last Date}}', Utilities.formatDate(new Date(lastDate),'GMT-5','MM-dd-yyyy'));

The valueOf() a string is different than the valueOf() a Date() object
Utilities.formatDate() returns a string not a Date() object
Try rewritting the section this way:
var firstDate = new Date(2075,01,01);
var lastDate = new Date(2000,01,01);
tables.forEach(table => {
if(table.getCell(0,0).getText() == "Date"){
rows.forEach(function(row,index){
var dt = new Date(row[0]);
var date1 = new Date(dt.getFullYear(),dt.getMonth(), dt.getDate());
if (date1.valueOf() < firstDate.valueOf()) firstDate = date1;
if (date1.valueOf() > lastDate.valueOf()) lastDate = date1;
You have to be careful with valueOf() because a lot of functions have a valueOf() function but they are different for different types of objects

Related

DateTime fromMillisecondsSinceEpoch returning Incorrect Values

So, I'm working on a converter for changing JDE Julian Dates to Gregorian Dates and Vice Versa. I've run into a weird problem that I cannot find an answer for in my Julian to Gregorian code where non-leap years are calculating as leap years and leap years are calculating as non-leap years.
Exp: When I enter the JDE Julian Date '122095' it should return 04/05/2022 but instead returns 04/06/2022. When I changed the year to 2020, a leap year, it returned todays correct date of 04/05/2022 when it should have returned 04/04/2020.
I think the problem might be with my DateTime.fromMillisecondsSinceEpoch converter because it is return 2022-04-06 06:00:00.000Z and I don't know where the 6 in the hour spot is coming from or how to cancel it out. My Code is below.
Edit: I forgot, I used the code originally from THIS post.
Edit Edit: Okay that fixed the problem, I set "var millisecondsSinceEpoch = DateTime(convYear()).millisecondsSinceEpoch;" to "var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;" and it was still giving me the wrong answer. I then thought to take the "isUtc: True" off of the end of "var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear));" and that fixed the issue. The best I can figure is having the UTC bool at the end of that line was preventing millisecondsSinceEpoch from actually converting to UTC.
Thanks jamesdlin and James Heap for your help!
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
gregDate(var inputDate) {
var inputDate = '122095';
// Break down JDE date into individual pieces
var currentYear = int.parse(DateFormat('yy').format(DateTime.now()));
print('Current Year: $currentYear');
var splitYear = int.parse(inputDate.substring(1, 3));
print('Split Year: $splitYear');
var splitDay = int.parse(inputDate.substring(3, inputDate.length));
print('Split Day: $splitDay');
// Uses the current year to determine if our 2 digit date needs a 19 or 20 in the front
convYear() {
if (splitYear <= currentYear) {
var year = '20' + splitYear.toString();
return int.parse(year);
}
else {
var year = '19' + splitYear.toString();
return int.parse(year);
}
}
print('Converted Year: ${convYear()}');
// Takes 3 digit day in year and converts it to formatted date time.
convDate() {
var dayOfYear = splitDay;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
print(millisInADay);
var millisDayOfYear = dayOfYear * millisInADay;
print(millisDayOfYear);
var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;
print(millisecondsSinceEpoch);
var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear), isUtc: true);
var result = DateFormat('MM/dd/${convYear()}').format(dayOfYearDate);
print(dayOfYearDate);
print(result);
return result;
}
return convDate();
}

how to calculate difference between two date and get year month and days in flutter

How can I change the Date format in dart
I get the from and to date difference value is int. How to change this integer to date format... and convert it to 0Days 0Months 7days;
I need this type of format
but I got this type of format
see the Vehicle Age:
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
age = doPurchase.difference(doRenewel).abs().inDays.toInt();
return age;
}
That is my function...
Use this package time_machine and try this code
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
LocalDate a = LocalDate.dateTime(doPurchase);
LocalDate b = LocalDate.dateTime(doRenewel);
Period diff = b.periodSince(a);
return "${diff.years} Years ${diff.months} Months ${diff.days} Days";
}
Try with this
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
Duration parse = doPurchase.difference(doRenewel).abs();
return "${parse.inDays~/360} Years ${((parse.inDays%360)~/30)} Month ${(parse.inDays%360)%30} Days";
}
Correct Answer
I got a correct answer use jiffy package.
import 'package:jiffy/jiffy.dart';
then use this code
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
var dt1 = Jiffy(doPurchase);
var dt2 = Jiffy(doRenewel);
int years = int.parse("${dt2.diff(dt1, Units.YEAR)}");
dt1.add(years: years);
int month = int.parse("${dt2.diff(dt1, Units.MONTH)}");
dt1.add(months: month);
var days = dt2.diff(dt1, Units.DAY);
return "$years Years $month Month $days Days";
}

Changing Pentaho date values to first and last day of the week in Javascript Modified Value

I am trying to set two variables to the first and last day of the week for a given date, but the .setDate() method does not seem to be changing the date and 'lastday' and 'firstday' variables return an Invalid Date (1970)
DateNew is from my input step which is defined as dd/MM/yyyy format
var curr = DateNew;
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
Declaring the input variable as a date seemed to resolve the issue as there was no javascript type associated with it.
var curr = new Date(DateNew);
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

Swift 2 for loop low and high date between

I have Array ;
var mydates : [String] = []
let startDate = "2018-03-01"
let endDate = "2018-03-03"
And I have 3 variable , startDate, endDate, dates , i want to append that variables, like;
if startDate = 2018-03-01, and endDate = 2018-03-03
will be add dates variable inside = "2018-03-01,2018-03-02,2018-03-03" between all dates from start and end dates.
How can i do it in swift 2 any idea ?
Here is Solution for Print all dates between two Date (Swift 4 Code)
var mydates : [String] = []
let startDate = "2018-03-01"
let endDate = "2018-03-05"
var dateFrom = Date() // First date
var dateTo = Date() // Last date
// Formatter for printing the date, adjust it according to your needs:
let fmt = DateFormatter()
fmt.dateFormat = "yyy-MM-dd"
dateFrom = fmt.date(from: startDate)!
dateTo = fmt.date(from: endDate)!
while dateFrom <= dateTo {
mydates.append(fmt.string(from: dateFrom))
dateFrom = Calendar.current.date(byAdding: .day, value: 1, to: dateFrom)!
}
print(mydates) // Your Result
Output is:
["2018-03-01", "2018-03-02", "2018-03-03", "2018-03-04", "2018-03-05"]

Difference of two locale date in jquery

I am getting the date from CJuidatepicker with language such de,en,nl.
Now i need to find the difference between two dates in jquery accordnig to the language selected.
My Code is
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate()-1;
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day;
var dateString1 = $('#Jobs_valid_date').val();
var dateString2= output;
var dateDiff = function ( dateString2, dateString1 ) {
var diff = Math.abs(dateString2 - dateString1);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000);
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000);
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000);
} else {
return "< 1 minute";
}
};
var new_date = dateDiff(new Date(dateString2), new Date(dateString1));
var sum = (parseInt(new_date * feature) + parseInt(fixed))
It retuns NAN.. Please help me to solve this
Doing it from scratch is not recommended for several reasons. If using a library is not a constraint, use moment.js. It has methods to calculate date differences. It has internationalization support too. In case your locale is not supported you can add it yourself. If you add a new locale, you are welcome to contribute it to the moment.js community.
Try this out, this worked for me. I wanted to calculate difference between the 2 dates which the client inputs.
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}