Time range
TimeRange is a simple class that holds from
and to
DateTime values. It's
designed to be helpful for filters when filtering data. For example, in Flutter,
it'd be useful to pattern match against the different time range
classes. For example:
Future<void> pickRange() async {
final TimeRange? range = await switch(range) {
YearTimeRange yearRange => pickYear(...),
MonthTimeRange monthRange => pickYearMonth(...),
LocalWeekTimeRange weekRange => pickWeek(...),
DayTimeRange dayRange => pickDate(...),
HourTimeRange hourRange => pickDateAndHour(...),
CustomTimeRange custom => pickRange(...),
_ => null,
}
if(!mounted) return;
setState(() => currentRange = range);
}
You can easily iterate through time ranges (except CustomTimeRange
) like so:
final LocalWeekTimeRange thisWeek = TimeRange.thisLocalWeek();
// If you have generic type variable, check using `is PageableRange`
final TimeRange generic = ...;
final TimeRange? nextRange = generic is PageableRange ? (generic as PageableRange).next : null;
moment_dart
is still a Dart library, and can be used without Flutter
Methods
-
toUtc()
Returns new instance in UTC timezone, or
this
ifthis.isUtc == true
.warningAll
TimeRange
s store the relevant info (e.g.,year
) and constructDateTime
based on that information. This means.toUtc()
will behave differently than you might expect.TimeRange().toUtc().from != TimeRange().from.toUtc();
TimeRange().toUtc().to != TimeRange().to.toUtc();However, the above isn't true for
CustomTimeRange
, which stores actualDateTime
object, and transforms it. -
contains(DateTime point)
Returns whether this range contains a point in time (inclusive)
-
containsRange(TimeRange other)
Returns whether this range contains the other range (inclusive)
Getters
-
next
Returns a new instance of the next interval.
Not available for
CustomTimeRange
. -
last
Returns a new instance of the last interval.
Not available for
CustomTimeRange
. -
isUtc
Returns whether the range is in UTC timezone.
Not available for
LocalWeekTimeRange
orIsoWeekTimeRange
, and will throwUnsupportedError
when called. -
duration
Returns how long the TimeRange spans
-
from
Beggining of the TimeRange
-
to
Ending of the TimeRange (last microsecond)
Create an instance
CustomTimeRange(from, to)
LocalWeekTimeRange
IsoWeekTimeRange
YearTimeRange
MonthTimeRange
DayTimeRange
HourTimeRange
- Static methods:
TimeRange.thisHour()
TimeRange.nextHour()
TimeRange.lastHour()
TimeRange.today()
TimeRange.tomorrow()
TimeRange.yesterday()
TimeRange.today()
TimeRange.tomorrow()
TimeRange.yesterday()
TimeRange.thisMonth()
TimeRange.nextMonth()
TimeRange.lastMonth()
TimeRange.thisYear()
TimeRange.nextYear()
TimeRange.lastYear()