栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

日期时间-获取下一个星期二

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

日期时间-获取下一个星期二

正如我在评论中提到的那样,“下一个星期二”可能意味着多种含义,但是这段代码为您提供了“下一个星期二发生,或者如果今天已经是星期二,则显示为今天”:

DateTime today = DateTime.Today;// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) today.DayOfWeek + 7) % 7;DateTime nextTuesday = today.AddDays(daysUntilTuesday);

如果要给“一周的时间”(如果已经是星期二),则可以使用:

// This finds the next Monday (or today if it's Monday) and then adds a day... so the// result is in the range [1-7]int daysUntilTuesday = (((int) DayOfWeek.Monday - (int) today.DayOfWeek + 7) % 7) + 1;

…或者您可以使用原始公式,但是从明天开始:

DateTime tomorrow = DateTime.Today.AddDays(1);// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]int daysUntilTuesday = ((int) DayOfWeek.Tuesday - (int) tomorrow.DayOfWeek + 7) % 7;DateTime nextTuesday = tomorrow.AddDays(daysUntilTuesday);

编辑:只是为了使这个漂亮和通用:

public static DateTime GetNextWeekday(DateTime start, DayOfWeek day){    // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]    int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;    return start.AddDays(daysToAdd);}

因此,要获取“今天或未来6天”的值:

DateTime nextTuesday = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);

获取“下一个星期二(今天除外)”的值:

DateTime nextTuesday = GetNextWeekday(DateTime.Today.AddDays(1), DayOfWeek.Tuesday);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/447198.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号