本文介绍了如何计算C#中的第二个星期五的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我已经写了一个控制台实用程序,将一行插入文本文件。我想要这一行包括当月的第二个星期五。有没有办法这样做?

I've wrote a little console utility that spits out a line into a text file. I want this line to include the second Friday of the current month. Is there any way to do this?

感谢大家!

推荐答案

@druttka的轻微变化:使用扩展方法。

Slight variation on @druttka: using an extension method.

 public static DateTime NthOf(this DateTime CurDate, int Occurrence , DayOfWeek Day)
 {
     var fday = new DateTime(CurDate.Year, CurDate.Month, 1);

     var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);
     // CurDate = 2011.10.1 Occurance = 1, Day = Friday >> 2011.09.30 FIX. 
     if (fOc.Month < CurDate.Month) Occurrence = Occurrence+1;
     return fOc.AddDays(7 * (Occurrence - 1));
 }

然后像这样调用:

 for (int i = 1; i < 13; i++)
 {
      Console.WriteLine(new DateTime(2011, i,1).NthOf(2, DayOfWeek.Friday));
 }

这篇关于如何计算C#中的第二个星期五的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 09:16