如何获得本周开始的日期时间? [英] How can I get the DateTime for the start of the week?

查看:20
本文介绍了如何获得本周开始的日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中只知道当前时间,找到一周的开始(周日和周一)?

How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?

类似于:

DateTime.Now.StartWeek(Monday);

推荐答案

使用扩展方法.他们是一切的答案,你知道!;)

Use an extension method. They're the answer to everything, you know! ;)

public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
}

可以如下使用:

DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);

这篇关于如何获得本周开始的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆