使用给定的DateTime对象获取一个月的第一天和最后一天

时间:2022-10-16 09:51:44

I want to get the first day and last day of the month where a given date lies in. The date comes from a value in a UI field.

我想要得到一个月的第一天和最后一天,在那里有一个给定的日期。日期来自UI字段中的值。

If I'm using a time picker I could say

如果我用的是时间选择器

var maxDay = dtpAttendance.MaxDate.Day;

But I'm trying to get it from a DateTime object. So if I have this...

但是我试图从DateTime对象中获取它。如果我有这个。

DateTime dt = DateTime.today;

How to get first day and last day of the month from dt?

如何从dt得到第一天和最后一天?

11 个解决方案

#1


314  

DateTime structure stores only one value, not range of values. MinValue and MaxValue are static fields, which hold range of possible values for instances of DateTime structure. These fields are static and does not relate to particular instance of DateTime. They relate to DateTime type itself.

DateTime结构只存储一个值,而不是值的范围。MinValue和MaxValue是静态字段,它们为DateTime结构的实例保存可能的值范围。这些字段是静态的,与DateTime的特定实例无关。它们与DateTime类型本身相关。

Suggested reading: static (C# Reference)

建议阅读:静态(c#引用)

UPDATE: Getting month range:

更新:月范围:

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

#2


60  

This is more a long comment on @Sergey and @Steffen's answers. Having written similar code myself in the past I decided to check what was most performant while remembering that clarity is important too.

这是对@Sergey和@Steffen的答案的长篇大论。我自己以前也写过类似的代码,所以我决定检查什么是最有效的,同时记住清晰也是很重要的。

Result

Here is an example test run result for 10 million iterations:

这里有一个1000万次迭代的测试运行结果示例:

2257 ms for FirstDayOfMonth_AddMethod()
2406 ms for FirstDayOfMonth_NewMethod()
6342 ms for LastDayOfMonth_AddMethod()
4037 ms for LastDayOfMonth_AddMethodWithDaysInMonth()
4160 ms for LastDayOfMonth_NewMethod()
4212 ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()
2491 ms for LastDayOfMonth_SpecialCase()

Code

I used LINQPad 4 (in C# Program mode) to run the tests with compiler optimization turned on. Here is the tested code factored as Extension methods for clarity and convenience:

我使用LINQPad 4(在c#程序模式下)在打开编译器优化的情况下运行测试。下面是经过测试的代码,作为清晰和方便的扩展方法:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth_AddMethod(this DateTime value)
    {
        return value.Date.AddDays(1 - value.Day);
    }

    public static DateTime FirstDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }

    public static DateTime LastDayOfMonth_AddMethod(this DateTime value)
    {
        return value.FirstDayOfMonth_AddMethod().AddMonths(1).AddDays(-1);
    }

    public static DateTime LastDayOfMonth_AddMethodWithDaysInMonth(this DateTime value)
    {
        return value.Date.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - value.Day);
    }

    public static DateTime LastDayOfMonth_SpecialCase(this DateTime value)
    {
        return value.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - 1);
    }

    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }

    public static DateTime LastDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, DateTime.DaysInMonth(value.Year, value.Month));
    }

    public static DateTime LastDayOfMonth_NewMethodWithReuseOfExtMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

void Main()
{
    Random rnd = new Random();
    DateTime[] sampleData = new DateTime[10000000];

    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = new DateTime(1970, 1, 1).AddDays(rnd.Next(0, 365 * 50));
    }

    GC.Collect();
    System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethodWithDaysInMonth();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethodWithDaysInMonth()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethodWithReuseOfExtMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()", sw.ElapsedMilliseconds).Dump();

    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = sampleData[i].FirstDayOfMonth_AddMethod();
    }

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_SpecialCase();
    }
    string.Format("{0} ms for LastDayOfMonth_SpecialCase()", sw.ElapsedMilliseconds).Dump();

}

Analysis

I was surprised by some of these results.

我对其中一些结果感到惊讶。

Although there is not much in it the FirstDayOfMonth_AddMethod was slightly faster than FirstDayOfMonth_NewMethod in most runs of the test. However, I think the latter has a slightly clearer intent and so I have a preference for that.

虽然里面没有太多内容,但是在大多数测试中,月的第一天添加方法比月的第一天添加方法快一些。然而,我认为后者的意图更明确一些,所以我更喜欢后者。

LastDayOfMonth_AddMethod was a clear loser against LastDayOfMonth_AddMethodWithDaysInMonth, LastDayOfMonth_NewMethod and LastDayOfMonth_NewMethodWithReuseOfExtMethod. Between the fastest three there is nothing much in it and so it comes down to your personal preference. I choose the clarity of LastDayOfMonth_NewMethodWithReuseOfExtMethod with its reuse of another useful extension method. IMHO its intent is clearer and I am willing to accept the small performance cost.

4 .上月的新方法与上月的新方法、上月的新方法和上月的新方法相比,无疑是一个失败者。在跑得最快的三个之间没有什么东西,所以这取决于你个人的喜好。我选择LastDayOfMonth_NewMethodWithReuseOfExtMethod的清晰度,它重用了另一个有用的扩展方法。它的意图更明确,我愿意接受这个小的性能成本。

LastDayOfMonth_SpecialCase assumes you are providing the first of the month in the special case where you may have already calculated that date and it uses the add method with DateTime.DaysInMonth to get the result. This is faster than the other versions, as you would expect, but unless you are in a desperate need for speed I don't see the point of having this special case in your arsenal.

LastDayOfMonth_SpecialCase假设您在特殊情况下提供了一个月的第一个月,您可能已经计算了这个日期,它使用了add方法和DateTime。在每个月的第一天得到结果。这比其他版本要快,正如你所期望的那样,但是除非你迫切需要速度,否则我不认为在你的兵工厂里有这种特殊情况是有意义的。

Conclusion

Here is an extension method class with my choices and in general agreement with @Steffen I believe:

这里有一个扩展方法类,我有我的选择,并且我相信与@Steffen的一般一致:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }

    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }

    public static DateTime LastDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

If you have got this far, thank you for time! Its been fun :¬). Please comment if you have any other suggestions for these algorithms.

如果你已经走了这么远,谢谢你的时间!它很有趣:¬)。如果您对这些算法有任何其他建议,请发表意见。

#3


10  

Getting month range with .Net API (just another way):

使用。net API获取月份范围(换句话说):

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

#4


4  

DateTime dCalcDate = DateTime.Now;
dtpFromEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, 1);
dptToEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, DateTime.DaysInMonth(dCalcDate.Year, dCalcDate.Month));

#5


3  

"Last day of month" is actually "First day of *next* month, minus 1". So here's what I use, no need for "DaysInMonth" method:

“月的最后一天”实际上是“下个月*的第一天,减去1”。这就是我所使用的,不需要"DaysInMonth"方法:

public static DateTime FirstDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, 1);
}

public static DateTime LastDayOfMonth(this DateTime value)
{
    return value.FirstDayOfMonth()
        .AddMonths(1)
        .AddMinutes(-1);
}

NOTE: The reason I use AddMinutes(-1), not AddDays(-1) here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59 so your report works correctly - including all the data from last day of month.

注意:我之所以使用AddMinutes(1),不是AddDays(1)这是,因为通常你需要这些日期函数date-period报告,当你建立一个报告在一段时间内,“结束日期”应该是类似于2015年10月31日23:59:59,所以你的报告正常工作——包括所有的数据从月的最后一天。

I.e. you actually get the "last moment of the month" here. Not Last day.

也就是说,你在这里得到了“这个月的最后一刻”。不是最后一天。

OK, I'm going to shut up now.

好吧,我现在就闭嘴。

#6


2  

Here you can add one month for the first day of current month than delete 1 day from that day.

在这里,你可以为当月的第一天添加一个月,而不是从那天删除一天。

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

#7


1  

The accepted answer here does not take into account the Kind of the DateTime instance. For example if your original DateTime instance was a UTC Kind then by making a new DateTime instance you will be making an Unknown Kind instance which will then be treated as local time based on server settings. Therefore the more proper way to get the first and last date of the month would be this:

这里接受的答案不考虑DateTime实例的类型。例如,如果您的原始DateTime实例是UTC类型的,那么通过创建一个新的DateTime实例,您将创建一个未知的类实例,然后根据服务器设置将其作为本地时间处理。因此,获得第一个月和最后一个月日期的正确方法是:

var now = DateTime.UtcNow;
var first = now.Date.AddDays(-(now.Date.Day - 1));
var last = first.AddMonths(1).AddTicks(-1);

This way the original Kind of the DateTime instance is preserved.

这样就可以保留DateTime实例的原始类型。

#8


1  

If you only care about the date

如果你只关心日期

var firstDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind);
var lastDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind).AddMonths(1).AddDays(-1);

If you want to preserve time

如果你想保留时间。

var firstDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind);
var lastDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind).AddMonths(1).AddDays(-1);

#9


0  

For Persian culture

波斯文化

PersianCalendar pc = new PersianCalendar();            
        var today = pc.GetDayOfMonth(DateTime.Now);
        var firstDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddDays(-(today-1)));
        var lastDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddMonths(1).AddDays(-today));            
        Console.WriteLine("First day "+ firstDayOfMonth);
        Console.WriteLine("Last day " + lastDayOfMonth);

#10


-1  

Try this one:

试试这个:

string strDate = DateTime.Now.ToString("MM/01/yyyy");

#11


-2  

easy way to do it

这很简单

Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month,1).ToShortDateString();
End = new DataFim.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToShortDateString();

#1


314  

DateTime structure stores only one value, not range of values. MinValue and MaxValue are static fields, which hold range of possible values for instances of DateTime structure. These fields are static and does not relate to particular instance of DateTime. They relate to DateTime type itself.

DateTime结构只存储一个值,而不是值的范围。MinValue和MaxValue是静态字段,它们为DateTime结构的实例保存可能的值范围。这些字段是静态的,与DateTime的特定实例无关。它们与DateTime类型本身相关。

Suggested reading: static (C# Reference)

建议阅读:静态(c#引用)

UPDATE: Getting month range:

更新:月范围:

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);

#2


60  

This is more a long comment on @Sergey and @Steffen's answers. Having written similar code myself in the past I decided to check what was most performant while remembering that clarity is important too.

这是对@Sergey和@Steffen的答案的长篇大论。我自己以前也写过类似的代码,所以我决定检查什么是最有效的,同时记住清晰也是很重要的。

Result

Here is an example test run result for 10 million iterations:

这里有一个1000万次迭代的测试运行结果示例:

2257 ms for FirstDayOfMonth_AddMethod()
2406 ms for FirstDayOfMonth_NewMethod()
6342 ms for LastDayOfMonth_AddMethod()
4037 ms for LastDayOfMonth_AddMethodWithDaysInMonth()
4160 ms for LastDayOfMonth_NewMethod()
4212 ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()
2491 ms for LastDayOfMonth_SpecialCase()

Code

I used LINQPad 4 (in C# Program mode) to run the tests with compiler optimization turned on. Here is the tested code factored as Extension methods for clarity and convenience:

我使用LINQPad 4(在c#程序模式下)在打开编译器优化的情况下运行测试。下面是经过测试的代码,作为清晰和方便的扩展方法:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth_AddMethod(this DateTime value)
    {
        return value.Date.AddDays(1 - value.Day);
    }

    public static DateTime FirstDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }

    public static DateTime LastDayOfMonth_AddMethod(this DateTime value)
    {
        return value.FirstDayOfMonth_AddMethod().AddMonths(1).AddDays(-1);
    }

    public static DateTime LastDayOfMonth_AddMethodWithDaysInMonth(this DateTime value)
    {
        return value.Date.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - value.Day);
    }

    public static DateTime LastDayOfMonth_SpecialCase(this DateTime value)
    {
        return value.AddDays(DateTime.DaysInMonth(value.Year, value.Month) - 1);
    }

    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }

    public static DateTime LastDayOfMonth_NewMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, DateTime.DaysInMonth(value.Year, value.Month));
    }

    public static DateTime LastDayOfMonth_NewMethodWithReuseOfExtMethod(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

void Main()
{
    Random rnd = new Random();
    DateTime[] sampleData = new DateTime[10000000];

    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = new DateTime(1970, 1, 1).AddDays(rnd.Next(0, 365 * 50));
    }

    GC.Collect();
    System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].FirstDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for FirstDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_AddMethodWithDaysInMonth();
    }
    string.Format("{0} ms for LastDayOfMonth_AddMethodWithDaysInMonth()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethod()", sw.ElapsedMilliseconds).Dump();

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_NewMethodWithReuseOfExtMethod();
    }
    string.Format("{0} ms for LastDayOfMonth_NewMethodWithReuseOfExtMethod()", sw.ElapsedMilliseconds).Dump();

    for(int i = 0; i < sampleData.Length; i++) {
        sampleData[i] = sampleData[i].FirstDayOfMonth_AddMethod();
    }

    GC.Collect();
    sw.Restart();
    for(int i = 0; i < sampleData.Length; i++) {
        DateTime test = sampleData[i].LastDayOfMonth_SpecialCase();
    }
    string.Format("{0} ms for LastDayOfMonth_SpecialCase()", sw.ElapsedMilliseconds).Dump();

}

Analysis

I was surprised by some of these results.

我对其中一些结果感到惊讶。

Although there is not much in it the FirstDayOfMonth_AddMethod was slightly faster than FirstDayOfMonth_NewMethod in most runs of the test. However, I think the latter has a slightly clearer intent and so I have a preference for that.

虽然里面没有太多内容,但是在大多数测试中,月的第一天添加方法比月的第一天添加方法快一些。然而,我认为后者的意图更明确一些,所以我更喜欢后者。

LastDayOfMonth_AddMethod was a clear loser against LastDayOfMonth_AddMethodWithDaysInMonth, LastDayOfMonth_NewMethod and LastDayOfMonth_NewMethodWithReuseOfExtMethod. Between the fastest three there is nothing much in it and so it comes down to your personal preference. I choose the clarity of LastDayOfMonth_NewMethodWithReuseOfExtMethod with its reuse of another useful extension method. IMHO its intent is clearer and I am willing to accept the small performance cost.

4 .上月的新方法与上月的新方法、上月的新方法和上月的新方法相比,无疑是一个失败者。在跑得最快的三个之间没有什么东西,所以这取决于你个人的喜好。我选择LastDayOfMonth_NewMethodWithReuseOfExtMethod的清晰度,它重用了另一个有用的扩展方法。它的意图更明确,我愿意接受这个小的性能成本。

LastDayOfMonth_SpecialCase assumes you are providing the first of the month in the special case where you may have already calculated that date and it uses the add method with DateTime.DaysInMonth to get the result. This is faster than the other versions, as you would expect, but unless you are in a desperate need for speed I don't see the point of having this special case in your arsenal.

LastDayOfMonth_SpecialCase假设您在特殊情况下提供了一个月的第一个月,您可能已经计算了这个日期,它使用了add方法和DateTime。在每个月的第一天得到结果。这比其他版本要快,正如你所期望的那样,但是除非你迫切需要速度,否则我不认为在你的兵工厂里有这种特殊情况是有意义的。

Conclusion

Here is an extension method class with my choices and in general agreement with @Steffen I believe:

这里有一个扩展方法类,我有我的选择,并且我相信与@Steffen的一般一致:

public static class DateTimeDayOfMonthExtensions
{
    public static DateTime FirstDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, 1);
    }

    public static int DaysInMonth(this DateTime value)
    {
        return DateTime.DaysInMonth(value.Year, value.Month);
    }

    public static DateTime LastDayOfMonth(this DateTime value)
    {
        return new DateTime(value.Year, value.Month, value.DaysInMonth());
    }
}

If you have got this far, thank you for time! Its been fun :¬). Please comment if you have any other suggestions for these algorithms.

如果你已经走了这么远,谢谢你的时间!它很有趣:¬)。如果您对这些算法有任何其他建议,请发表意见。

#3


10  

Getting month range with .Net API (just another way):

使用。net API获取月份范围(换句话说):

DateTime date = ...
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

#4


4  

DateTime dCalcDate = DateTime.Now;
dtpFromEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, 1);
dptToEffDate.Value = new DateTime(dCalcDate.Year, dCalcDate.Month, DateTime.DaysInMonth(dCalcDate.Year, dCalcDate.Month));

#5


3  

"Last day of month" is actually "First day of *next* month, minus 1". So here's what I use, no need for "DaysInMonth" method:

“月的最后一天”实际上是“下个月*的第一天,减去1”。这就是我所使用的,不需要"DaysInMonth"方法:

public static DateTime FirstDayOfMonth(this DateTime value)
{
    return new DateTime(value.Year, value.Month, 1);
}

public static DateTime LastDayOfMonth(this DateTime value)
{
    return value.FirstDayOfMonth()
        .AddMonths(1)
        .AddMinutes(-1);
}

NOTE: The reason I use AddMinutes(-1), not AddDays(-1) here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59 so your report works correctly - including all the data from last day of month.

注意:我之所以使用AddMinutes(1),不是AddDays(1)这是,因为通常你需要这些日期函数date-period报告,当你建立一个报告在一段时间内,“结束日期”应该是类似于2015年10月31日23:59:59,所以你的报告正常工作——包括所有的数据从月的最后一天。

I.e. you actually get the "last moment of the month" here. Not Last day.

也就是说,你在这里得到了“这个月的最后一刻”。不是最后一天。

OK, I'm going to shut up now.

好吧,我现在就闭嘴。

#6


2  

Here you can add one month for the first day of current month than delete 1 day from that day.

在这里,你可以为当月的第一天添加一个月,而不是从那天删除一天。

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

#7


1  

The accepted answer here does not take into account the Kind of the DateTime instance. For example if your original DateTime instance was a UTC Kind then by making a new DateTime instance you will be making an Unknown Kind instance which will then be treated as local time based on server settings. Therefore the more proper way to get the first and last date of the month would be this:

这里接受的答案不考虑DateTime实例的类型。例如,如果您的原始DateTime实例是UTC类型的,那么通过创建一个新的DateTime实例,您将创建一个未知的类实例,然后根据服务器设置将其作为本地时间处理。因此,获得第一个月和最后一个月日期的正确方法是:

var now = DateTime.UtcNow;
var first = now.Date.AddDays(-(now.Date.Day - 1));
var last = first.AddMonths(1).AddTicks(-1);

This way the original Kind of the DateTime instance is preserved.

这样就可以保留DateTime实例的原始类型。

#8


1  

If you only care about the date

如果你只关心日期

var firstDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind);
var lastDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind).AddMonths(1).AddDays(-1);

If you want to preserve time

如果你想保留时间。

var firstDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind);
var lastDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind).AddMonths(1).AddDays(-1);

#9


0  

For Persian culture

波斯文化

PersianCalendar pc = new PersianCalendar();            
        var today = pc.GetDayOfMonth(DateTime.Now);
        var firstDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddDays(-(today-1)));
        var lastDayOfMonth = pc.GetDayOfMonth(DateTime.Now.AddMonths(1).AddDays(-today));            
        Console.WriteLine("First day "+ firstDayOfMonth);
        Console.WriteLine("Last day " + lastDayOfMonth);

#10


-1  

Try this one:

试试这个:

string strDate = DateTime.Now.ToString("MM/01/yyyy");

#11


-2  

easy way to do it

这很简单

Begin = new DateTime(DateTime.Now.Year, DateTime.Now.Month,1).ToShortDateString();
End = new DataFim.Text = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToShortDateString();