how to Calculate sum of multiple durations moment-js? - express

I am tryng to calculate w total working hours of each user what I did is getting the duration of each day, now I want to calculate the total working hours Given this input
durations:[ '0:30:00', '0:30:00', '0:30:00', '1:00:00' ] being respectively half an hour each and the last element being one hour ,
now I want to be able to sum all of these duration to get the total working hours
Here's what I managed to do to get the duration I am open to all of your suggestions to improve my already existing code and get my wanted result which is totalHours=HH:mm:ss
let startTime = moment(book.startTime, 'hh:mm:ss');
let endTime = moment(book.endTime, 'hh:mm:ss');
let totalSec = endTime.diff(startTime, 'seconds');
var durations = moment()
.startOf('day')
.seconds(totalSec)
.format('H:mm:ss');
result.push(durations);

Convert each duration to miliseconds
Get the sum of those miliseconds
Create moment object to format to hms
const durations = [ '0:30:00', '0:30:00', '0:30:00', '1:00:00' ];
const ms = durations.map(d => moment.duration(d).asSeconds() * 1000);
const sum = ms.reduce((prev, cur) => prev + cur, 0);
const hms = moment.utc(sum).format("HH:mm:ss");
console.log('HMS: ' + hms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data.min.js"></script>
HMS: 02:30:00

Related

Youtrack workflow via JS - Unable to compare estimation and spent time

I just want to compare 2 periods (e.g. i want to compare between 3w4d23h58m and 20h in order to track time). All i got is
I need to convert this PT2H to just 2 hours to count percentage between estimation and spent time.
https://www.jetbrains.com/help/youtrack/devportal/v1-PeriodProjectCustomField.html?q=getMinutes
Here is an excerpt from a workflow that calculates remaining time by subtracting spent time from estimation:
action: (ctx) => {
const issue = ctx.issue;
var periodestimate = issue.Estimation;
var minutesestimate = !periodestimate ? 0 : (periodestimate.getMinutes() + 60 * (periodestimate.getHours() + 8 * (periodestimate.getDays() + 5 * periodestimate.getWeeks())));
var periodspent = ctx.issue.fields.SpentTime;
var minutesspent = !periodspent ? 0 : (periodspent.getMinutes() + 60 * (periodspent.getHours() + 8 * (periodspent.getDays() + 5 * periodspent.getWeeks())));
var remain = minutesestimate - minutesspent;
ctx.issue.fields.Remaining = dateTime.toPeriod(remain + 'm');
},
I suppose that you can use it as an example to calculate the needed percentage.

Arcade expressions for diplay in Collector

I am working to create a 'Number of Days Open' indicator using ESRI's Collector app. It needs to display the Maximum and Mean values for the number of days a request has been open. However, the table only provides the Date that a request was opened. The number of days a request has been open can be determined using the DateDiff function, but I am having trouble with the full table of values approx. 20,000.
Any help would be greatly appreciated.
var today = Now();
var startdate = $datapoint["created_at"];
var numberdays = DateDiff (today, startdate, 'days');
var Big = Max(numberdays);
var Middle = Mean(numberdays);
return {
textColor:'',
backgroundColor:'',
topText:'Avg: ' + Middle,
topTextColor: '',
topTextOutlineColor: '',
topTextMaxSize: 'medium',
middleText: 'Max: '+ Big,
middleTextColor: '',
middleTextOutlineColor: '',
middleTextMaxSize: 'medium',
}

Moment JS seemingly returning random date

Moment JS is returning a random date.
I am trying to create a calendar in a react-native project. I created this loop to count back the days from today's date. I have attached my console and tried to clearly show how I tried to debug this.
The subtract method seems not to recognise the loop and the i value seems to stay at 16.
Any help would be greatly appreciated.
This is the code that is causing all the fussThis is the output in the console
Per Moment.js, moments are mutable. Clone the moment before performing date math
https://momentjs.com/guides/#/lib-concepts/mutability/
You'll need to create a new moment instance or clone the existing one when performing operations like .add(), .subtract(), etc.
const moment = require("moment");
const today = moment();
// count back N days
const N = 3;
let i = 1;
let days = [];
// #1 - Create a new moment instance from today and add -i days
while (i <= N) {
const day = moment(today).add(-i, "days");
days.push(day);
i++;
}
console.log("Approach #1");
console.log({ days });
// #2 - A moment is mutable. So we use add() to mutate today by -1 days each iteration, clone the instance, and push to array
i = 0;
days = [];
while (i < N) {
const day = today.add(-1, "days").clone();
days.push(day);
i++;
}
console.log("Approach #2");
console.log({ days });

Calculate the difference between two dates in React Native

I need to calculate the difference between two dates in days
i bring today date: new Date().toJSON().slice(0, 10) = 2019-04-17
and the other date in the same form
var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime(); //Future date - current date
var daysTill30June2035 = Math.floor(msDiff / (1000 * 60 * 60 * 24));
console.log(daysTill30June2035);
You can implement it yourself, but why would you? The solution to that already exists, and somebody else has taken care (and still is taking care) that it works as it should.
Use date-fns.
import differenceInDays from 'date-fns/difference_in_days';
If you really want to bash your head, you can get difference in milliseconds and then divide by number of milliseconds in a day. Sounds good to me, but I'm not 100% sure if it works properly.
const differenceInDays = (a, b) => Math.floor(
(a.getTime() - b.getTime()) / (1000 * 60 * 60 * 24)
)
If you manipulate many dates, maybe an external library like moment.js could be useful. There are multiple add-ons like the date range one.
Once installed, you need to create a range
const start = new Date(2011, 2, 5);
const end = new Date(2011, 5, 5);
const range = moment.range(start, end);
Then could get the difference by doing something like
range.diff('months'); // 3
range.diff('days'); // 92
range.diff(); // 7945200000
Hope it could be useful :)
var d1 = new Date("2019/04/17") //firstDate
var d2 = new Date("2011/02/01") //SecondDate
var diff = Math.abs(d1-d2); //in milliseconds
Use differenceInDays, parseISO from "date-fns"
import DateTimePicker from "#react-native-community/datetimepicker";
import { differenceInDays, parseISO } from "date-fns";
let day = differenceInDays(
parseISO(your end date),
parseISO(yout first Date)
);
console.log("differenceInDays",differenceInDays)

FullCalendar V4 - How to account for shorter months in a recurring event series?

I'm using FullCalendar v4-alpha-3 with the RRule plugin to generate recurring events. It works as expected with only one problem: how do I modify a recurring event to account for months with fewer days than the starting month in a series?
For example, if the first monthly occurrence happens on January 29, 2019; the event will be repeated on the 29th of all subsequent months except in February since it only has 28 days (leap years excluded).
I've tried resetting dtstart to the first day of the following month. It works, except the event is no longer recursive.
Here's a stripped down snippet of my setup:
let calendar = new Calendar(calendarEl, {
plugins: [ rrulePlugin ],
events: [
{
rrule: 'DTSTART:20190129 RRULE:FREQ=MONTHLY;UNTIL=20200130;COUNT=13;BYMONTHDAY=29'
}
],
eventRender: function(info) {
...
// reset start date to the first day of the following month
// if current month has fewer days than base month
let start = event.start;
let day = start.getDate();
let now = new Date();
let currentMonth = now.getMonth();
let currentYear = now.getFullYear();
let daysInCurrent = getDaysInMonth(currentMonth + 1, currentYear);
let nextStart = start;
if (day > daysInCurrent) {
nextStart = new Date(currentYear, currentMonth + 1, 1);
event.setStart(nextStart);
event.setEnd(null);
}
}
});
I'd appreciate any insight.
Not quite the solution I hoped for, but RRule's bysetpos property seems to offer the next best alternative as it allows for a fallback date in case the one specified doesn't exist.
For example, the following would generate an occurrence on the 30th of every month; or the last day of the month if the 30th doesn’t exist:
FREQ=MONTHLY;BYMONTHDAY=28,29,30;BYSETPOS=-1.
Sourced from: https://icalevents.com/2555-paydays-last-working-days-and-why-bysetpos-is-useful/
I know this is an old question but maybe this will be usefull for someone:
I'm using momentjs library
monthly:
let endofmonth = moment('2020-02-29', "YYYY-MM-DD").endOf('month').format('DD');
let curday = moment('2020-02-29, "YYYY-MM-DD").format('DD');
single_event.title = title;
single_event.rrule = {};
single_event.rrule.freq = 'monthly';
single_event.rrule.dtstart = start_date;
single_event.rrule.interval = reminder_interval;
single_event.rrule.count = reminder_count;
if(endofmonth == curday){
// Checking if given day of the month is last
single_event.rrule.byweekday = ['mo','tu','we','th','fr','sa','su'];
single_event.rrule.bysetpos = -1;
}
else{
single_event.rrule.bymonthday = parseInt(curday);
}
calendar_events.push(single_event);
var calendar = new FullCalendar.Calendar(calendarEl, {
...
events: calendar_events
});
yearly:
single_event.title = title;
single_event.rrule = {};
single_event.rrule.dtstart = start_date;
single_event.rrule.count = parseInt(reminder_count);
if(endofmonth == curday){
// Checking if given day of the month is last
single_event.rrule.freq = 'monthly'; // Will work as yearly if interval is 12
single_event.rrule.interval = parseInt(reminder_interval)*12;
single_event.rrule.bymonthday = [28,29,30,31];
single_event.rrule.bysetpos = -1;
}
else{
single_event.rrule.freq = 'yearly';
single_event.rrule.bymonthday = parseInt(curday);
}
calendar_events.push(single_event);
var calendar = new FullCalendar.Calendar(calendarEl, {
...
events: calendar_events
});