1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-24 22:09:21 +00:00
comunicmobile/lib/utils/date_utils.dart

78 lines
2.2 KiB
Dart
Raw Permalink Normal View History

2019-04-23 14:38:41 +00:00
import 'package:comunic/utils/intl_utils.dart';
2021-03-13 07:17:54 +00:00
import 'package:intl/intl.dart';
2019-04-23 14:38:41 +00:00
/// Date utilities
///
/// @author Pierre HUBERT
/// Get current timestamp
int time() {
return (DateTime.now().millisecondsSinceEpoch / 1000).floor();
}
String? diffTimeToStr(int amount) {
2019-04-23 14:38:41 +00:00
if (amount < 0) amount = 0;
// Seconds
if (amount < 60) return tr("%secs%s", args: {"secs": amount.toString()});
// Minutes
if (amount < 60 * 60)
return tr("%mins% min", args: {"mins": (amount / 60).floor().toString()});
// Hours
if (amount < 60 * 60 * 24)
return tr("%hours% h",
args: {"hours": (amount / (60 * 60)).floor().toString()});
// Days
if (amount < 60 * 60 * 24 * 30)
return tr("%days%d",
args: {"days": (amount / (60 * 60 * 24)).floor().toString()});
// Months
if (amount < 60 * 60 * 24 * 365) {
final months = (amount / (60 * 60 * 24 * 30)).floor();
return months == 1
? tr("1 month")
: tr("%months% months", args: {"months": months.toString()});
}
// Years
final years = (amount / (60 * 60 * 24 * 365)).floor();
2021-03-10 23:02:41 +00:00
return years == 1
? tr("1 year")
: tr("%years% years", args: {"years": years.toString()});
2019-04-23 14:38:41 +00:00
}
String? diffTimeFromNowToStr(int date) {
2019-04-23 14:38:41 +00:00
return diffTimeToStr(time() - date);
}
2019-04-26 06:58:18 +00:00
/// Return properly formatted date and time
String dateTimeToString(DateTime time) {
return "${time.day}:${time.month}:${time.year} ${time.hour}:${time.minute}";
2021-03-10 23:02:41 +00:00
}
/// Format a [Duration] in the form "MM:SS"
String formatDuration(Duration d) =>
"${d.inMinutes < 10 ? "0" + d.inMinutes.toString() : d.inMinutes.toString()}:${d.inSeconds % 60 < 10 ? "0" + (d.inSeconds % 60).toString() : (d.inSeconds % 60).toString()}";
2021-03-13 07:17:54 +00:00
/// Compare two [DateTime] on their date
bool isSameDate(DateTime one, DateTime? other) {
2021-03-13 07:17:54 +00:00
if (other == null) return false;
return one.year == other.year &&
one.month == other.month &&
one.day == other.day;
}
/// Format a date to make it easily shown
String formatDisplayDate(DateTime dt, {bool date = true, bool time = true}) {
final format = Intl(Intl.systemLocale).date();
if (date) {
format.add_EEEE();
format.add_yMMMMd();
}
if (time) format.add_jm();
return format.format(dt);
}