【问题标题】:Finding date for given year,month and day name in c# [closed]在c#中查找给定年、月和日名称的日期[关闭]
【发布时间】:2016-03-12 08:54:21
【问题描述】:

如果给出了年、月和日,我如何在 c# 中找到日期。

例如给定月份 = 03,年份 = 2016。我需要找到星期六发生的日期。

预期输出[我们可以看到 2016/03 的星期六发生在以下日期]:
2016 年 5 月 3 日
2016 年 12 月 3 日
2016 年 3 月 19 日
26/03/2016

【问题讨论】:

  • 你也许应该先开始研究它。
  • This 应该会有所帮助。
  • @AliK:谢谢它的帮助。
  • @YassinHajaj :我已经根据 Alik 的建议进行了研究,并找到了解决方案。

标签: c# datetime


【解决方案1】:
List<DateTime> saturdays = new List<DateTime>();
        for(int i=0;i<DateTime.DaysInMonth(year, month), i++)
        {
            DateTime dt = new DateTime(year, month, i);
            if (dt.DayOfWeek == DayOfWeek.Saturday)
                saturdays.Add(dt);
        }

【讨论】:

    【解决方案2】:

    使用 Linq,不假设一个月的天数:

        static IEnumerable<DateTime> GetSaturdaysInMonth(int year, int month)
        {
            return Enumerable.Range(1, DateTime.DaysInMonth(year, month))
                .Select(day => new DateTime(year, month, day))
                .Where(dt => dt.DayOfWeek == DayOfWeek.Saturday);
        }
    

    【讨论】:

      【解决方案3】:
      int year = 2016, month = 3;
      DayOfWeek dayOfWeek = DayOfWeek.Saturday;
      var dates = 
          // generate dates for all days in the month
          Enumerable.Range(1, DateTime.DaysInMonth(year, month))
          .Select(x => new DateTime(year, month, x))
          // select only those of particular dayOfWeek
          .Where(d => d.DayOfWeek == dayOfWeek)
          .ToList();
      

      【讨论】:

        【解决方案4】:

        您可以根据年份和月份变量创建一个DateTime 作为该月的第一天,遍历下个月的第一天并检查它的DayOfWeek property 是否为Saturday。喜欢;

        var month = 3;
        var year = 2016;
        
        var start = new DateTime(year, month, 1);
        var end = start.AddMonths(1);
        
        while (start < end)
        {
            if (start.DayOfWeek == DayOfWeek.Saturday)
            {
                Console.WriteLine(start.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
            }
            start = start.AddDays(1);
        }
        

        打印

        05/03/2016
        12/03/2016
        19/03/2016
        26/03/2016
        

        【讨论】:

          【解决方案5】:

          这是一种(非常简单的)可能性:

          var startDate = new DateTime(2016, 3, 1);
          var list = new List<DateTime>();
          for(int i = 0; i < DateTime.DaysInMonth(2016, 3); i++) {
              var date = startDate.AddDays(i);
              if (date.DayOfWeek == DayOfWeek.Saturday) list.Add(date);
          }
          

          您使用该月的第一天创建 startDate。
          然后您遍历该月的所有日子并将星期六添加到列表中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-29
            • 1970-01-01
            • 1970-01-01
            • 2023-03-23
            • 1970-01-01
            相关资源
            最近更新 更多