How do I work out how many days ago date1 was compared to date2, using datejs? - datejs

var d1 = Date.parse(date); // eg, 7th jan
var d2 = Date.today(); // eg, 2nd jan
I want to do:
(d2 - d1).days
which with the above data, should return 5.
Is this possible with datejs?

The optional TimeSpan module includes functionality to easily get various value differences between two date objects.
http://code.google.com/p/datejs/source/browse/trunk/src/time.js
Just include after your main date.js include, or combine.
In the "time.js" file, there's also a TimePeriod class. You might not require, so just crop what you need if weight is an issue.
The following sample demonstrates the full scenario.
Example
var d1 = Date.parse("jan 7"); // eg, 7th jan
var d2 = Date.parse("jan 2"); // eg, 2nd jan
console.log(new TimeSpan(d1 - d2).days); // 5
Hope this helps.

Related

Issue with date formatting and time zone change

I am having a weird issue with dates formatting in Google Sheets and Google Script.
I am developing a script that reads a list of dates in a Google sheet and then sends automatic emails to a list of recipients. I have a cell in the spreadsheet with a date formatted as "dd/mm/yyyy" and then I use the following formulas (cell + 7, cell + 14, cell + 21, cell + 28, etc...) to generate all the other dates in the spreadsheet.
I use the following code to read the dates in the spreadsheet:
var sheet = SpreadsheetApp.getActiveSheet();
var drng = sheet.getDataRange();
var rng = sheet.getRange(4, 2, drng.getLastRow()-3, drng.getLastColumn());
var rngData = rng.getValues();
var todayDate = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy");
// CYCLE THROUGH DATA
for (var i = 0; i < rngData.length; i++) { // cycle through the rows in the spreadsheet
var ptLastName = rngData[i][0]; // fixed patient data used to email customization
var ptFirstName = rngData[i][1];
var ptDoB = Utilities.formatDate(rngData[i][2], "GMT+1", "dd/MM/yyyy");
var ptSex = rngData[i][3];
var ptEmail = rngData[i][4];
var ptDoS = Utilities.formatDate(rngData[i][5], "GMT+1", "dd/MM/yyyy");
var ptDoD = Utilities.formatDate(rngData[i][6], "GMT+1", "dd/MM/yyyy");
for (var j = 7; j <= 14; j++) { // cycle through follow-up data for the current patient
var currentDate = Utilities.formatDate(rngData[i][j], "GMT+1", "dd/MM/yyyy");
if (currentDate == todayDate) { // send email with the questionnaire
writeEmail(ptFirstName, ptLastName, ptSex, ptDoD, ptEmail);
rng.getCell(i+1, j+1).setBackground("yellow");
}
}
}
The issue is that when I try for read and format some of the dates they are not corresponding to the ones listed in the spreadsheet. I have noted that the wrong dates in the code are systematically 1 day earlier than the ones listed in the spreadsheet. On a closer look I have noted that some of the dates read from the spreadsheet at GMT+2 while others are GMT+1.
That's weird because I have checked my system settings (it GMT+1) as well as the spreadsheet settings (GMT+1). So I don't understand why some dates are automatically converted to GMT+2.
I tried it this way and it works okay:
function dattest() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getActiveSheet();
const rg=sh.getDataRange();
const vs=rg.getValues()[0];
vs.forEach(function(d){
Logger.log(Utilities.formatDate(new Date(d),Session.getScriptTimeZone(),"dd/MM/yyyy"));
});
}
Display Values:
8/1/2020,8/8/2020,8/15/2020,8/22/2020
Formulas:
,=A1+7,=A1+14,=a1+21
The output from view Executions:
Aug 1, 2020, 2:52:37 PM Info 01/08/2020
Aug 1, 2020, 2:52:37 PM Info 08/08/2020
Aug 1, 2020, 2:52:37 PM Info 15/08/2020
Aug 1, 2020, 2:52:37 PM Info 22/08/2020
Seems correct to me
thank you for your help.
I finally found out what the problem was.
The dates in the spreadsheet were stored as dd/mm/yyyy, and the system automatically added 00.00.00 as time to them. As a result, when I was trying to read some of the dates with the code some of them were converted as the day before because of the daylight saving time adjustment. I have managed to solve the issue adding 1/3 of a day to all the dates. This way they are stored as dd/mm/yyyy 8.00.000 am and they remain the same day all year long.

momentjs calculates date difference incorrectly

In my angular web application, I want to compare two dates to see if a person is less than 18 years old when she/he entered the company. Here is the code I use to do this:
const dayOfBirth = moment(formControl.value, this.dateFormat, true).startOf('day');
const entranceDateControl = this.wizardFormGroup.get('entranceDate');
const entranceDate = moment(entranceDateControl.value, this.dateFormat, true).startOf('day');
// Check validation rule R3: Age is less than 18 compared to entrance date
const difference = moment.duration(Math.abs(entranceDate.diff(dayOfBirth)));
if (difference.years() < 18) {
const validationMessage = this.getValidationMessage('R3', formControlName);
return validationMessage ? validationMessage.message : null;
}
As you can see, I am using startOf('day') to get rid of any time component so that I only handle dates. I use diff() to get the difference between two dates and then duration() to convert the difference to years, months, days, etc. Using this code, the validation message should NOT show when the person is turning 18 years old on the day when she/he entered the company.
Upon testing this, I came across what is, in my opinion, strange behavior. Depending on months and years used, it gave different results. For instance, for these dates it was Ok:
dayOfBirth = 1998-03-01, 1998-04-01, ..., 2000-02-01
entranceDate = 2016-03-01, 2016-04-01, ..., 2018-02-01
But the following dates returned the validation message:
dayOfBirth = 2000-03-01, 2000-04-01, ..., 2002-02-01
entranceDate = 2018-03-01, 2000-04-01, ..., 2020-02-01
After these dates, i.e. using 2002-03-01 and onward, it works again. I also got wrong result for the dates preceding 1998-03-01.
Now, I had a closer look at the Duration object and I noticed that for the times where it was less than 18 years, it had calculated 864 milliseconds less then when it came to the right conclusion that it was 18 years between the dates.
Correct duration
----------------
dayOfBirth = 1998-03-01, 1998-04-01, ..., 2000-02-01
entranceDate = 2016-03-01, 2016-04-01, ..., 2018-02-01
Duration = 568080000000 ms
Wrong duration
--------------
dayOfBirth = 2000-03-01, 2000-04-01, ..., 2002-02-01
entranceDate = 2018-03-01, 2000-04-01, ..., 2020-02-01
Duration = 567993600000 ms
Duration difference
-------------------
568080000000 - 567993600000 = 86400000 ms = 24 hours = 1 day
Has anyone an explanation for this? Can it be considered a bug in momentjs? Any viable workaround for this?
I didn't go into details in moment source code but it seems duration() is playing tricks with you. Simplify the code and rely only on diffas follow and you should be good (at least it seems to work for the samples you provided). And it's easier on the eyes :)
const moment = require('moment')
const dayOfBirth = moment('2000-03-01').startOf('day');
const entranceDate = moment('2018-03-01').startOf('day');
const difference = entranceDate.diff(dayOfBirth, 'years')
if (difference < 18) {
console.log( '<18')
} else {
console.log( '>=18')
}
will output >=18

Bosun how to add series with different tags?

I'm trying to add 4 series using bosun expressions. They are from 1,2,3,4 weeks ago. I shifted them using shift() to have current time. But I can't add them since they have the shift=1w etc tags. How can I add these series together?
Thank you
edit: here's the query for 2 weeks
$period = d("1w")
$duration = d("30m")
$week1end = tod(1 * $period )
$week1start = tod(1 * $period + $duration )
$week2end = tod(2 * $period )
$week2start = tod(2 * $period + $duration )
$q1 = q("avg:1m-avg:os.cpu{host=myhost}", $week1start, $week1end)
$q2 = q("avg:1m-avg:os.cpu{host=myhost}", $week2start, $week2end)
$shiftedq1 = shift($q1, "1w")
$shiftedq2 = shift($q2, "2w")
$shiftedq1+ $shiftedq2
edit: here's what Bosun said
The problem is similar to: How do I add the series present in the output of an over query:
over("avg:1m-avg:os.cpu{host=myhost}", "30m", "1w", 2)
There is a new function called addtags that is pending documentation (see https://raw.githubusercontent.com/bosun-monitor/bosun/master/docs/expressions.md for draft) which seems to work when combined with rename. Changing the last line to:
$shiftedq1+addtags(rename($shiftedq2,"shift=shiftq2"),"shift=1w")
should generate a single result group like { host=hostname, shift=1w, shiftq2=2w }. If you add additional queries for q3 and q4 you probably need to rename the shift tag for those to unique values like shiftq3 and shiftq4.
If you were using a numbersets instead of seriessets, then the Transpose function would let you "Drop" the unwanted tags. This is useful when generating alerts, since crit and warn need a single number value not a series set:
$average_per_q = avg(merge($shiftedq1,$shiftedq2))
$sum_over_all = sum(t($average_per_q,"host"))
Result: { host=hostname } 7.008055555555557
Side note you probably want to use a counter for os.cpu instead of a gauge. Example: $q1 = q("avg:1m-avg:rate{counter,,1}:os.cpu{. Without that rate section you are using the raw counter values instead of the gauge value.

Getting the month number by month name with Moment.js

I am trying to return the month number passing the month name using MomentJS. For example if I pass "July" to moment() I would expect 7 to be returned.
After reading through the docs I tried several different ways, and this way came close...
console.log(moment().month("July"));
In the console, buried in the response I could see this...
_monthsParse: Array[7]
Could anyone please tell me how to return the month number using MomentJS correctly?
Try :
moment().month("July").format("M");
Relevant documentation: http://momentjs.com/docs/#/get-set/month/
alert(moment().month("July").format("M"));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Anybody looking to get month name from month number then you can try :
const number = 1; // 0 = Jan & 11 = Dec
moment().month(number).format("MMM"); // Feb
Use following to get full month name :
const number = 1; // 0 = January & 11 = December
moment().month(number).format("MMMM"); // February
To use simple month number try this:
const month = 2 //Feb
moment(month, 'M').format('MMMM');
##get month name in moment js with node js
moment() give today date
format("DD-MMMM-YYYY") / output 18-May-2020
format("DD-MM-YYYY") / output 18-05-2020
- sperator you can use /
```
var moment = require('moment');
m_date = moment().format("DD-MMMM-YYYY");
console.log("moment date :", m_date)
```
##output
```
moment date : 18-May-2020
```
Read Officail Docdescription here

Adobe flex dateField

I have some code as follows:
private function onComboChange(evt:Event):void {
var temp:Date = df_date.selectedDate;
temp.date += 5;
df_dateDue.selectedDate = new Date(temp);
}
In essence, I am trying to add 5 days onto the selected date in df_date, and put that date into df_dateDue. This fires off via an EventListener on a combobox. Both df_date and df_dateDue are dateFields.
OK, so the first time that I run this, it works fine; df_date stays the same and df_dateDue is set to 5 days past df_date. However, the next time that I run it, df_dateDue increments by 10 days from df_date, the next time by 15, and so on.
So, stepping through the code shows that somehow df_date has become linked to the temp var, and that the temp var is not resetting itself each time the function is called.
Example: df_date = 01 Jan, df_dateDue = 01 Jan.
Fire off the event, df_date = 01 Jan, df_dateDue = 06 Jan
Fire off the event again. At this point, var temp = 06 Jan (even though df_date still shows 01 Jan), and df_dateDue is then set to 11 Jan
Fire off the event again. At this point var temp = 11 Jan (even though df_date = 01 Jan), and df_dateDue is then set to 16 Jan
What am I missing here?
In Flex/AS, variables that contain objects are really just pointers to some memory space. Date's in Flex are an Object, not a native type. This line:
var temp:Date = df_date.selectedDate;
Creates a new pointer to an existing date object. It does not create a copy.
This line:
temp.date += 5;
increments the date property of the dateObject. All references pointing to that date object will be updated. Try using objectUtil.copy
var temp:Date = ObjectUtil.copy(df_date.selectedDate) as Date;
Oh, and get your acceptance rate up.

Resources