如何计算C#中的第二个星期五 [英] How to calculate 2nd Friday of Month in C#

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

问题描述


可能重复:

如何找到一个月的第三个星期五与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#中的第二个星期五的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆