How to split two times using frequency in dart? - datetime

So, I need partition two times in dart(startTime and endTime) using an int value called frequency
Start time and End Time are DateTimes respectively. As for an example:
start time: 2021-07-20 10:00:00.000 // 10:00 AM
end time: 2021-07-20 16:00:00.000 // 04:00 PM
frequency: 30
so I need a list which will give my something like:
2021-07-20 10:30:00.000
2021-07-20 11:00:00.000
2021-07-20 11:30:00.000
2021-07-20 12:00:00.000
2021-07-20 12:30:00.000
.......
I have no idea what to do next. But I have created a method called returnTimeDifference which goes something like this:
Duration returnDuration (DateTime? startTime , DateTime? endTime) {
print(
"start time: $startTime \nend Time: $endTime",
);
Duration hourSpan;
workHourSpan = endTime!.difference(startTime !);
print(hourSpan);
return hourSpan;
}
For my above example the method will return 6:00:00.000000. I'm not sure if the value returned from the returnDuration can be used in any matter but I need help splitting the values of two date times into parts using the provided frequency.
N.B: Will it be easier to calculate the values if frequency was in actual Duration?

Repeatedly add your time interval to your start time in a loop until you reach the end time and collect the results. Using a Duration instead of an int for your time interval will be easier and will avoid ambiguity (in your example code, it's unclear if frequency represents a time in minutes, seconds, or if it's supposed to be the number if items you want in the resulting list).
Assuming that your start time and end time are meant to be exclusive endpoints, you could do:
/// Returns a list of [DateTime]s between (but not including) [start] and
/// [end], spaced by [period] intervals.
List<DateTime> getDateTimesBetween({
required DateTime start,
required DateTime end,
required Duration period,
}) {
var dateTimes = <DateTime>[];
var current = start.add(period);
while (current.isBefore(end)) {
dateTimes.add(current);
current = current.add(period);
}
return dateTimes;
}
void main() {
print(getDateTimesBetween(
start: DateTime(2021, 07, 20, 10),
end: DateTime(2021, 07, 20, 16),
period: Duration(minutes: 30),
));
}

Related

Opensearch painless calculate elpased time between two timestamp

I have start and end timestamp, and I want to calculate the elpased time between them.
I created a dinamic field elapsed-time:
def result = 0;
def endTimestamp = doc['endTimestamp'].value.millis;
def startTimestamp = doc['startTimestamp'].value.millis;
return (endTimestamp - startTimestamp );
When I discover data, the elapsed time has always bad hours, but minutes and seconds are right.
What I am doing wrong?

How to create an event series with a start date and an end date

First of all, sorry if my English isn't good as I'm a french guy.
I have a problem with a google script I took on the internet that automatically inputs holliday in my calendar.
Let me explain in detail: I use a google form to get all the data I need to input my calendar, such as the name of the employee, the start date of his holliday, the end date, and other information like mail and stuff. The start date and end date are with hours to indicate at which hour start and finish the holliday.
Here's my problem, I use CreateEventSeries but when I use this, it creates a "bar" until the end date but I would like to have an event day by day, until the end date, that finish at 18pm.
Here's the code i use :
else if (approval == Approval.Approved && reason == Reason.Vacation) {
CalendarApp.getCalendarById(email)
.createEventSeries(
'CP',
startDate,
endDate,
CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([CalendarApp.Weekday.MONDAY, CalendarApp.Weekday.TUESDAY, CalendarApp.Weekday.WEDNESDAY, CalendarApp.Weekday.THURSDAY, CalendarApp.Weekday.FRIDAY])
.until(endDate),
{
description: message,
sendInvites: true,
}
);
// Send a confirmation email.
let subject = 'Congés acceptés';
MailApp.sendEmail(additionalEmail, subject, message, );
row[Header.NotifiedStatus] = NotifiedStatus.Notified;
Logger.log(`Approved, calendar event created, row=${JSON.stringify(row)}`);
}
I don't know if I made myself clear.
I don't want an all-day event cause it's not visible enough on the calendar.
In short, I would like to create an event series day by day from 8 am until 18pm with a start date and an end date.
Does someone have a solution or a lead?
Best regards
Issue:
When creating an event series via createEventSeries(title, startTime, endTime, recurrence, options), the parameters startTime and endTime refer to the start and end time of the first event in the series, not of the series as a whole:
startTime: the date and time when the first event in the series starts
endTime: the date and time when the first event in the series ends
This endTime is completely different from what you want to set at until(endDate), which refers to when the series of events will finish.
Code snippet:
For example, if you want to have an event every day that lasts from 8 AM to 6 PM, from, let's say, 1 to 15 May, you would do this:
const startTime = new Date('May 1, 2021 08:00:00 GMT+01:00');
const endTime = new Date('May 1, 2021 18:00:00 GMT+01:00');
const endDate = new Date('May 15, 2021 18:00:00 GMT+01:00');
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
Update:
Assuming you have installed an onFormSubmit trigger, your function could be something like this:
function createEventSeriesOnSubmit(e) {
const formResponse = e.response;
let itemResponses = formResponse.getItemResponses();
const itemNames = ["startDate", "endDate", "startHour", "endHour"];
const responses = itemNames.map(itemName => getResponseForItem(itemResponses, itemName));
const [startDay, endDay, startHour, endHour] = responses;
const startTime = new Date(`${startDay} ${startHour}`);
const endTime = new Date(`${startDay} ${endHour}`);
const endDate = new Date(`${endDay} ${endHour}`);
const recurrence = CalendarApp.newRecurrence().addWeeklyRule()
.onlyOnWeekdays([
CalendarApp.Weekday.MONDAY,
CalendarApp.Weekday.TUESDAY,
CalendarApp.Weekday.WEDNESDAY,
CalendarApp.Weekday.THURSDAY,
CalendarApp.Weekday.FRIDAY
])
.until(endDate)
CalendarApp.getCalendarById(email).createEventSeries('CP',startTime,endTime,recurrence);
}
Where "startDate", "endDate", "startHour", "endHour" are the names of the corresponding items in your Form. For example:
As you can see in the code sample, you can build the corresponding date to use in calendar by interpolating the date response and the time response, like this:
const startTime = new Date(`${startDay} ${startHour}`);
The resulting calendar has the series of events corresponding to the start hour, end hour, start date and end date that have been specified:

How to get last 30 minutes,1 Hour time from the from current time in DART

how can I get the last 3 hours time from the current time in DART
I am getting the current time by this
DateTime toTime = new DateTime.now();
I want to get last last 30minutes before,lastOneHour,lastThreeHour,last 6,last 12,last 24 time from the current time.
I tried doing like this
from = toTime.subtract(new Duration(hours: 0.5)).millisecondsSinceEpoch;
//This is not working
I am converting those result to epochtime.
As #julemand101 pointed out, Duration has its named hours parameter as an int. Passing a double will toss an error. Instead, write your code something like this:
DateTime curTime = new DateTime.now(); //Current local time
DateTime thirtyMinAgo = curTime.subtract(Duration(minutes: 30));
int thirtyMinAgoInMs = thirtyMinAgo.millisecondsSinceEpoch;
return thirtyMinAgoInMs;
Try out this package, Jiffy. Inspired by momentjs. It also takes into account the leap years and how many days there are in each month
To get the last 30 minutes
Jiffy().subtract(minutes: 30);
// You can also add your DateTime object
Jiffy(DateTime.now()).subtract(minutes: 30);
To get the last 3 hours
Jiffy().subtract(hours: 3);
You can also get up to months and years
var jiffy = Jiffy()
.subtract(minutes: 30, hours: 3, days: 6, months: 2, years: 1);
print(jiffy.dateTime);
// Or you can format it on the go
print(jiffy.format("dd, MMM yyyy"));
print(jiffy.yMMMd);
Hope this helped.

moment.js Timezone Parsing and Comparison

I'm receiving timestamps in the following format '2016-08-17T14:00:00-04:00', which I can parse in moment with moment('2016-08-17T14:00:00-04:00', 'YYYY-MM-DDTHH:mm:ssZ').
But the problem is that I want to print out .format('LLLL') and have it read Wednesday, August 17, 2016 10:00 AM, i.e. subtracting -04:00 from 14:00:00 (NY from UTC). It appears that there is a _tzm: -240 property in the moment object that looks like it holds that -4 hours value, but how do I use that property?
The other goal is to be able to pass in the current time and test if it is between the startDate and endDate variables below. I am guessing if I can convert both to NY-EST I can do this, but I can't seem to get moment to accept the timezone parameter.
Any thoughts?
var moment = require('moment');
// Timestamp strings from API
var startDate = '2016-08-17T14:00:00-04:00';
var endDate = '2016-08-17T15:00:00-04:00';
// Create a range from the start and end dates
var range = moment().range(new Date(startDate), new Date(endDate));
// Get the current time
var currentTime = new Date();
// Does the current time fall within the range b/w the start and end dates
range.contains(currentTime);
A solution I found is below. Adding the value from momentObj._tzm to the parsed date.
module.exports.convertDateToProperTimezone = function (dt) {
var _m = moment(dt, 'YYYY-MM-DDTHH:mm:ssZ');
return _m.add(_m._tzm, 'minutes');
};

comparison of two dates

how to compare values of 2 dates using actionscript
i executed this code in my program..
var time1:Date = new Date(Number(fromDate.substr(0,4)),Number(fromDate.substring(5,7))-1, Number(fromDate.substring(8,10)));
var time2:Date = new Date(Number(toDate.substr(0,4)),Number(toDate.substring(5,7))-1, Number(toDate.substring(8,10)));
if(time1.getTime() > time2.getTime())
{
Alert.show(time1 + ” is after ” + time2);
}
im getting error: Error: Unexpected end of token stream
AS3 doesn't support a time delta class like Python so this can actually be a little tricky. There are lots of things to be worried about when comparing dates:
daylight savings time (when the clocks change one hour in certain countries Spring and Fall)
time-zones
leap-years
The roughest way to do things is just to use the time property of a date object. This way you can get an accurate difference between two dates expressed in milliseconds:
var date1:Date = new Date(2001, 9, 12); // Oct. 12, 2001
var date2:Date = new Date(2010, 5, 22); // Jun. 22, 2010
var differenceInMilliseconds:Number = date2.time - date1.time;
Using this time property you can do things like check if one date is before or after another date. You can also do rough calculations on the distance between two dates by defining some constants:
const MILLISECOND_PER_SECOND:int = 1000;
const SECOND_PER_MINUTES:int = 60;
const MINUTES_PER_HOUR:int = 60;
const HOURS_PER_DAY:int = 24;
// ... etc ...
var differenceInSeconds:Number = differenceInMilliseconds / MILLISECOND_PER_SECOND;
var differenceInMinutes:Number = differenceInSeconds / SECOND_PER_MINUTES;
var differenceInHouse:Number = differenceInMinutes / MINUTES_PER_HOUR;
var differenceInDays:Number = differenceInHouse / HOURS_PER_DAY;
Once you get to the level of days you could get problems with daylight savings time since the change of 1 hour can make it seem like a full day has passed when it really hasn't. After days and into weeks or months you run into leap year problems.
Assuming your string processing code correctly gives you valid date objects, just use the ObjectUtil.dateCompare function to compare 2 dates:
http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#dateCompare%28%29
if( ObjectUtil.dateCompare(date1, date2) == 1 ){}
I'm pretty sure that the return types defined in the ASDocs are wrong.
It'll actually return -1 if a is null or before b; 1 if b is null or before.
If you have two dates as Date objects already, just compare them. e.g. a.getTime() > b.getTime().
If they are strings, see their format is acceptable by the default Date.parse() function. If not, you may have other work to do.
Let's see your values first, shall we?
private function differenceBetweenDates(date1:Date, date2:Date):Number{
var MS_PER_DAY:uint = 1000 * 60 * 60 * 24;
var tempDate:Date = new Date(date2.time - date1.time);
var difference:Number =
Math.abs(Math.round((tempDate.time / MS_PER_DAY)));
return difference;
}
I have achieved comparing dates succesfully using below code:
//here i have to compare two dates ,these are startdate and enddate.
// gets millisecs counts from 1970 midnight till sellected start date
var Starttimecounts : Number = popJobWin.DFStartDate.selectedDate.time;
// gets millisecs counts from 1970 midnight till sellected end date
var Endtimecounts : Number = popJobWin.DFEndDate.selectedDate.time ;
if (Starttimecounts > Endtimecounts)
{
Alert.show('end date should not lesser than start date..wrong!');
//replace your logic here
}
else
{
Alert.show('correct!');
//replace your logic here
}

Resources