我有需要转换为C#的PHP代码。基本上它计算给定周的5个日期 PHP代码如下:
$period_week_start = new DateTime();
$monday = $period_week_start->setISODate(2016, 36)->format('Ymd');
$tuesday = $period_week_start->modify('+1 days')->format('Ymd');
输出
20160815
20160816
我正在使用的C#代码如下:
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).ToString("yyyyMMdd");
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday).ToString("yyyyMMdd");
输出
20160815
20160816
这确实给了我想要的输出但是我需要一种方法来传递“周没有”,这样我就能得到给定周的日期。
为了得到一周没有,我使用以下代码:
var currentCulture = CultureInfo.CurrentCulture;
var weekNo = currentCulture.Calendar.GetWeekOfYear(DateTime.Now,
currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek);
谢谢
答案 0 :(得分:1)
试试这个
public static DateTime[] WeekDaysFromWeekNo(int Year, int WeekNumber)
{
DateTime start = new DateTime(Year, 1, 1).AddDays(7 * WeekNumber);
start = start.AddDays(-((int)start.DayOfWeek));
return Enumerable.Range(1, 7).Select(num => start.AddDays(num)).ToArray();
}
您可以更改范围,以便在星期一到星期五之间说出来,依此类推,并按照您希望的方式格式化日期。