C# How can I check if today is the first Monday of the month?

前端 未结 5 1048
太阳男子
太阳男子 2021-01-01 12:04

How can I check if today is the first Monday of the month?

The code below gives me the last day of the month, how should I modify this?

DateTime toda         


        
相关标签:
5条回答
  • 2021-01-01 12:26

    I don't know c#, but in any language, it's

    if Today is monday, 
    and Today's Date is 7 or less.
    
    0 讨论(0)
  • 2021-01-01 12:31

    You could do the following

    DateTime dt = ...;
    if (dt.DayOfWeek == DayOfWeek.Monday && dt.Day <= 7) {
      // First Monday of the month
    }
    
    0 讨论(0)
  • 2021-01-01 12:42

    How about:

    DateTime today = DateTime.Today;
    if (today.DayOfWeek == DayOfWeek.Monday && today.Day <= 7)
    

    Finding the first Monday of the month is slightly trickier. It's not clear whether or not you need that - let us know if you need that.

    Note the use of DateTime.Today once - that way you don't end up with potential oddities where the date changes between the two parts of the condition being evaluated.

    0 讨论(0)
  • 2021-01-01 12:43
    bool isItFirstMonday = DateTime.Today.DayOfWeek == DayOfWeek.Monday 
                             && DateTime.Today.Day <= 7
    

    Edit: sorry, typo :)

    0 讨论(0)
  • 2021-01-01 12:44

    A related case is, as Jon said, slightly trickier. Presuming you know the year and month:

    public static DateTime getFirstMondayOfMonthAndYear(int Month, int Year)
    {
        DateTime dt;
        DateTime.TryParse(String.Format("{0}/{1}/1", Year, Month), out dt); 
        for (int i = 0; i < 7; i++)
            {
            if (dt.DayOfWeek == DayOfWeek.Monday)
            {
                return dt;
            }
            else
            {
                dt = dt.AddDays(1);
            }
            }
        // If get to here, punt
        return DateTime.Now;
    }
    
    0 讨论(0)
提交回复
热议问题