Skip to content

Instantly share code, notes, and snippets.

@NebulaFox
Last active December 24, 2018 18:07
Show Gist options
  • Save NebulaFox/8b3a9b37a29df81aaeadc6ccbe60acb9 to your computer and use it in GitHub Desktop.
Save NebulaFox/8b3a9b37a29df81aaeadc6ccbe60acb9 to your computer and use it in GitHub Desktop.
Dart / Duration
void main() {
final sunrise = Duration.fromTime(
hours:8,
seconds:39,
);
final dayLength = Duration.fromTime(
hours: 7,
minutes: 51,
seconds: 45
);
print(dayLength);
print(dayLength * 0.5);
print(sunrise + (dayLength * 0.5));
}
class Duration {
final double seconds;
Duration(this.seconds);
factory Duration.fromTime({
int hours = 0,
int minutes = 0,
int seconds = 0,
}) {
//convert to seconds
final s = hours * (60*60) + minutes * 60 + seconds;
return Duration(s.toDouble());
}
Duration operator +(Duration other) {
return Duration(seconds + other.seconds);
}
Duration operator -(Duration other) {
return Duration(seconds - other.seconds);
}
Duration operator /(num other) {
return Duration(seconds / other);
}
Duration operator *(num other) {
return Duration(seconds * other);
}
String toString() {
final h = (seconds / (60*60)).truncate();
final m = (seconds / 60).truncate() % 60;
final s = seconds % 60;
var str = "Duration($seconds)";
if (h != 0) {
str +=
" {hours:$h "
"minutes:$m "
"seconds:$s}";
} else if (m != 0) {
str +=
" {minutes:$m "
"seconds:$s}";
}
return str;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment