简体   繁体   English

在C#中获取上个月的第一天和最后一天的日期

[英]Get the previous month's first and last day dates in c#

I can't think of an easy one or two liner that would get the previous months first day and last day.我想不出一个简单的一两个班轮可以得到前几个月的第一天和最后一天。

I am LINQ-ifying a survey web app, and they squeezed a new requirement in.我正在 LINQ-ifying 一个调查网络应用程序,他们挤进了一个新的要求。

The survey must include all of the service requests for the previous month.调查必须包括上个月的所有服务请求。 So if it is April 15th, I need all of Marches request ids.因此,如果是 4 月 15 日,我需要所有 Marches 请求 ID。

var RequestIds = (from r in rdc.request 
                  where r.dteCreated >= LastMonthsFirstDate && 
                  r.dteCreated <= LastMonthsLastDate 
                  select r.intRequestId);

I just can't think of the dates easily without a switch.没有开关,我无法轻易想到日期。 Unless I'm blind and overlooking an internal method of doing it.除非我是盲人并且忽略了这样做的内部方法。

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

In-line them if you really need one or two lines. 如果你真的需要一两行就可以在线。

The way I've done this in the past is first get the first day of this month 我过去这样做的方式是先到本月的第一天

dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );

Then subtract a day to get end of last month 然后减去一天到上个月结束

dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);

Then subtract a month to get first day of previous month 然后减去一个月以获得上个月的第一天

dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime 使用Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

        var lastMonth = 1.Months().Ago().Date;
        var firstDayOfMonth = lastMonth.FirstDayOfMonth();
        var lastDayOfMonth = lastMonth.LastDayOfMonth();
DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);

I use this simple one-liner: 我用这个简单的单线程:

public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
    return date.AddDays(-date.Day);
}

Be aware, that it retains the time. 请注意,它保留了时间。

An approach using extension methods: 使用扩展方法的方法:

class Program
{
    static void Main(string[] args)
    {
        DateTime t = DateTime.Now;

        DateTime p = t.PreviousMonthFirstDay();
        Console.WriteLine( p.ToShortDateString() );

        p = t.PreviousMonthLastDay();
        Console.WriteLine( p.ToShortDateString() );


        Console.ReadKey();
    }
}


public static class Helpers
{
    public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
    {
        DateTime d = currentDate.PreviousMonthLastDay();

        return new DateTime( d.Year, d.Month, 1 );
    }

    public static DateTime PreviousMonthLastDay( this DateTime currentDate )
    {
        return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
    }
}

See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions. 有关一些灵感的DateTime扩展,请参阅此链接http://www.codeplex.com/fluentdatetime

The canonical use case in e-commerce is credit card expiration dates, MM/yy. 电子商务中的规范用例是信用卡到期日,MM / yy。 Subtract one second instead of one day. 减去一秒而不是一天。 Otherwise the card will appear expired for the entire last day of the expiration month. 否则,该卡将在到期月的整个最后一天显示已过期。

DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
  expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);

This is a take on Mike W's answer: 这是Mike W的回答:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so: 你可以像这样调用它:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);
DateTime now = DateTime.Now;
int prevMonth = now.AddMonths(-1).Month;
int year = now.AddMonths(-1).Year;
int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
  lastDayPrevMonth.ToShortDateString());

If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons... This will prevent you from missing any requests created during the date of Jan 31. 如果您的日期时间不是严格的日历日期,您应该考虑使用enddate排除比较...这将防止您错过在1月31日期间创建的任何请求。

DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);

var RequestIds = rdc.request
  .Where(r => lastMonth <= r.dteCreated)
  .Where(r => r.dteCreated < thisMonth)
  .Select(r => r.intRequestId);
var lastMonth = DateTime.Today.AddMonths(-1);
dRet1 = new DateTime(lastMonth.Year, lastMonth.Month, 1);
dRet2 = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM