如何更优雅地计算下周日午夜在达特的Epoch时间



当用户打开我的应用程序时,会有一个倒计时计时器,显示距离周日午夜(本周比赛结束时(还有多少时间。

为了获得倒计时中使用的初始值,我的代码在循环中将604800000(这是一周中的毫秒数(添加到1595203200000的起始值(这是自午夜任意一个过去周日的历元以来的毫秒(,直到它大于现在:

int now = DateTime.now().millisecondsSinceEpoch;
int nextSundayAtMidnight = 1595203200000; // starting value is from arbitrary past Sunday at midnight
while (now > nextSundayAtMidnight) {
print('now is still greater than nextSundayAtMidnight so adding another 604800000 until it's not');
nextSundayAtMidnight += 604800000;
}
print('nextSundayAtMidnight is $nextSundayAtMidnight');

它是有效的,但似乎应该有一种更好的方法,基于DateTime.now,而不必手动指定任意的起始值。有吗?

dart中有什么语法可以更优雅地做到这一点?

提前感谢!

下面的代码使用添加工作日的差异来获得即将到来的周日的日期,然后将确切的DateTime转换为晚上11:59:59。代码中有注释描述了每行的操作。

它使用了dart中DateTime类中已经提供的许多有用的方法。

void main()
{
var now = DateTime.now();
//Obtains a time on the date of next sunday
var nextSunday = now.add(Duration(days: DateTime.sunday - now.weekday));
//Shifts the time to being 11:59:59 pm on that sunday
var nextSundayMidnight = DateTime(nextSunday.year, nextSunday.month, nextSunday.day + 1).subtract(Duration(seconds: 1));

//Gets the difference in the time of sunday at midnight and now
var timeToSundayMidnight = nextSundayMidnight.difference(now);

print(timeToSundayMidnight);
}

最新更新