Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 什么';What’获得月初和月底日期的最简单方法是什么?_C#_.net_Datetime - Fatal编程技术网

C# 什么';What’获得月初和月底日期的最简单方法是什么?

C# 什么';What’获得月初和月底日期的最简单方法是什么?,c#,.net,datetime,C#,.net,Datetime,下面是我找到的最好的方法。思想?如果你把它加载并运行,有没有更快的方法让它加载,那么我在这里做了什么?我有什么遗漏吗 void Main() { Console.WriteLine(GetMonthStart(DateTime.Now)); Console.WriteLine(GetMonthEnd(DateTime.Now)); } private DateTime GetMonthStart(DateTime dt) { dt= dt.Date; return

下面是我找到的最好的方法。思想?如果你把它加载并运行,有没有更快的方法让它加载,那么我在这里做了什么?我有什么遗漏吗

void Main()
{
    Console.WriteLine(GetMonthStart(DateTime.Now));
    Console.WriteLine(GetMonthEnd(DateTime.Now));
}
private DateTime GetMonthStart(DateTime dt)
{
    dt= dt.Date;
    return dt.Subtract(TimeSpan.FromDays(dt.Day - 1));
}
private DateTime GetMonthEnd(DateTime dt)
{
    dt= dt.Date;
    return GetMonthStart(dt).AddMonths(1).Subtract(TimeSpan.FromTicks(1));
}

不确定是否更好,但我可能会这样做

private DateTime GetMonthStart(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, 1);
}

private DateTime GetMonthEnd(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
}

不确定是否更好,但我可能会这样做

private DateTime GetMonthStart(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, 1);
}

private DateTime GetMonthEnd(DateTime dt)
{
    return new DateTime(dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month));
}

询问意见的问题不适合StackExchange格式。请阅读我们的。您可能想在这里询问第一天:将目标日期传递到dateTime:new dateTime(dateTime.Year,dateTime.Month,1);询问意见的问题不适合StackExchange格式。请阅读我们的。您可能想在这里询问第一天:将目标日期传递到dateTime:new dateTime(dateTime.Year,dateTime.Month,1);这非常适合DateTime上的扩展方法这非常适合DateTime上的扩展方法