How to get first day and last day of previous month in C#?

Dung Do Tien May 29 2022 42

Hello guys. I'm working for an IT computer as an intern. I need to create an admin page that helps show detail and export data. The end-user can choose "Last month" option to see all data for the last month, I'm using C# LinQ to query like this:

public async Task<List<NotifyUsers>> Gets(int top)
{
    DateTime firstDayOfLastMonth = ......; // Need to define first day of last month here
    DateTime lastDayOfLastMonth = .......; // Need to define last day of last month here
    return await _db.NotifyUsers.Where(x => x.CreatedDate >= firstDayOfLastMonth && x.CreatedDate <= lastDayOfLastMonth)
        .Take(top).ToListAsync();
}

I don't know how to set value for firstDayOfLastMonth and lastDayOfLastMonth variables.

Anyone can help me?

Thank you in advance!

Have 2 answer(s) found.
  • S

    SunilKumar SJ May 29 2022

    I usually use this way:

    DateTime today = DateTime.Now;
    DateTime fistDayOfCurrentMonth = new DateTime(today.Year, today.Month, 1);
    DateTime firstDayOfLastMonth = fistDayOfCurrentMonth.AddMonths(-1);
    DateTime lastDayOfLastMonth = fistDayOfCurrentMonth.AddDays(-1);

     I hope it is useful for you.

  • P

    PIHU ROCKS May 29 2022

    Do you hear about FluentDateTime package in C#? It's very simple like this:

    var lastMonth = 1.Months().Ago().Date;
    var firstDayOfMonth = lastMonth.FirstDayOfMonth();
    var lastDayOfMonth = lastMonth.LastDayOfMonth();

    Happy code :D:D:D

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close