【问题标题】:How to get last week begin date and last month begin date in c#?如何在c#中获取上周开始日期和上个月开始日期?
【发布时间】:2011-03-10 06:43:09
【问题描述】:

我想在 c# 中检索基于上周和上个月的记录。上周我想要从周日到周六的记录。上个月我想获取上个月的开始日期以获取直到该月底的所有记录.

我不应该获取上周的最后六天记录,而是我想从当前周(星期日)开始日期查找最后一个星期日的日期。

我找到了找到上个月第一天和最后一天的解决方案---->

 var first = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddMonths(-1);
                    var last = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).AddDays(-1);

上周找到的----->

DateTime _currDateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified);
                    DateTime _currentDate;
                    DateTime _lastWeekStartDate;
                    _currentDate = _currDateTime.StartOfWeek(DayOfWeek.Sunday);
                    _lastWeekStartDate = _currentDate.AddDays(-1);
                    tempfromdate = _lastWeekStartDate.StartOfWeek(DayOfWeek.Sunday);
                    temptodate = tempfromdate.EndOfWeek(DayOfWeek.Saturday);

【问题讨论】:

  • 你如何定义周?不同的文化对它的定义不同。尤其是一周的第一天会有所不同。

标签: c#


【解决方案1】:

这至少是一种方法

DateTime lastWeekFirstDay = DateTime.Now.AddDays( - 6 - (int)DateTime.Now.DayOfWeek);
DateTime lastMonthFirstDay = DateTime.Now.AddMonths( -1 ).AddDays( 1 - DateTime.Now.Day);

如果星期日是您的文化中一周的第一天,请将第一行代码中的 6 替换为 7。 6 假设星期一是一周的第一天。

编辑

添加了可能更具可读性的月份变体的变体:

DateTime lastMonthFirstDay = new DateTime( DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1);

【讨论】:

  • 上个月第一天和最后一天的逻辑。上个月的逻辑工作。谢谢伙计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 2010-11-19
相关资源
最近更新 更多