我需要检查日期是否在两个日期之间。
我试图搜索它,但没有得到富有成效的结果。可能你见过这样的场景。所以,寻求你的建议。
这是我的代码。
var service_start_date = '2020-10-17';
var service_end_date = '2020-10-23';
var service_start_time = '10:00:00';
var service_end_time = '11:00:00';
DateTime currentDate = new DateTime.now();
DateTime times = DateTime.now();
@override
void initState() {
super.initState();
test();
}
test() {
String currenttime = DateFormat('HH:mm').format(times);
String currentdate = DateFormat('yyyy-mm-dd').format(currentDate);
print(currenttime);
print(currentdate);
}
Run Code Online (Sandbox Code Playgroud)
所以,基本上我有开始日期和结束日期。我需要检查当前日期是否介于这两个日期之间。
mar*_*987 17
我做了一系列的扩展
extension DateTimeExtension on DateTime? {
bool? isAfterOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isAfter(dateTime);
}
return null;
}
bool? isBeforeOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isBefore(dateTime);
}
return null;
}
bool? isBetween(
DateTime fromDateTime,
DateTime toDateTime,
) {
final date = this;
if (date != null) {
final isAfter = date.isAfterOrEqualTo(fromDateTime) ?? false;
final isBefore = date.isBeforeOrEqualTo(toDateTime) ?? false;
return isAfter && isBefore;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它们是不言自明的,但显然你可以这样称呼它们
DateTime.now().isBefore(yourDate)
DateTime.now().isAfter(yourDate)
DateTime.now().isBetween(fromDate, toDate)
KuK*_*uKu 10
您可以在“DateTime”类中使用“isBefore”和“isAfter”之前/之后检查。

DateTime startDate = DateTime.parse(service_start_date);
DateTime endDate = DateTime.parse(service_end_date);
DateTime now = DateTime.now();
print('now: $now');
print('startDate: $startDate');
print('endDate: $endDate');
print(startDate.isBefore(now));
print(endDate.isAfter(now));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2918 次 |
| 最近记录: |