首页 > 解决方案 > 如何使用日期格式获取每月的第一个星期日?

问题描述

嗨,我需要检查该月第一个星期日的条件,以获取格式为 YYYYMMDD 的日期

      var calDate = data.value; // example 20210502 is sunday 

      if (first Sunday of the month)
      {
         do this
      }
      else
      {
         do that
      }

我需要检查每月第一个星期日的上述情况

标签: c#

解决方案


Split your problem in two:

  1. parse the string to a DateTime object

var date = DateTime.ParseExact(calDate, "yyyyMMdd", null);

  1. Check if the DateTime object refers to the first sunday in a month. For this, it must obviously be a Sunday and the day part must be in the range 1 to 7:

var isFirstSunday = date.DayOfWeek == DayOfWeek.Sunday && date.Day <= 7;


推荐阅读