memor/lib/date_utils.dart

46 lines
1.2 KiB
Dart
Raw Normal View History

2020-05-21 20:25:25 +02:00
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
2020-05-23 10:58:06 +02:00
import 'localizations.dart';
2020-05-21 20:25:25 +02:00
/// Utilities for handling DateTime objects.
extension DateUtils on DateTime {
/// Create a new instance with identical values.
DateTime copy() => DateTime(
this.year,
this.month,
this.day,
this.hour,
this.minute,
);
/// Create a new instance with the same date but a different time.
DateTime copyWithTime(TimeOfDay time) => DateTime(
this.year,
this.month,
this.day,
time.hour,
time.minute,
);
2020-05-23 10:58:06 +02:00
/// Get a localized string representation of the represented day suitable for
/// display.
String dateString(BuildContext context) {
final l10n = MemorLocalizations.of(context);
2020-05-21 20:25:25 +02:00
final now = DateTime.now();
if (this.year == now.year && this.month == now.month) {
if (this.day == now.day) {
2020-05-23 10:58:06 +02:00
return l10n.today;
2020-05-21 20:25:25 +02:00
} else if (this.day == now.day + 1) {
2020-05-23 10:58:06 +02:00
return l10n.tomorrow;
2020-05-21 20:25:25 +02:00
}
}
2020-05-23 10:58:06 +02:00
final format = DateFormat.yMd(l10n.languageCode);
2020-05-21 20:25:25 +02:00
return format.format(this);
}
/// Get the time of day represented by this object.
TimeOfDay get timeOfDay => TimeOfDay.fromDateTime(this);
}