我如何才能获得本周四的星期日?例如,本周四是2010年7月8日
答案 0 :(得分:16)
您可以使用现有的.NET DateTime执行此操作(难以理解)。诀窍是使用DayOfWeek
枚举作为整数 - 因为它以升序数字顺序(0-6)表示太阳 - 星期六。
DateTime someDay = DateTime.Today;
var daysTillThursday = (int)someDay.DayOfWeek - (int)DayOfWeek.Thursday;
var thursday = someDay.AddDays( daysTillThursday );
甚至更简单:
var today = DateTime.Today;
var thursday = today.AddDays(-(int)today.DayOfWeek).AddDays(4);
答案 1 :(得分:2)
查看此库:http://datetimeextensions.codeplex.com/
来自主页上的示例:
DateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);
答案 2 :(得分:2)
DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek).AddDays(4)
答案 3 :(得分:1)
private static DateTime GetDayOfWeek(DayOfWeek dayOfWeek)
{
var date = DateTime.Now;
if (date.DayOfWeek != dayOfWeek)
{
var direction = date.DayOfWeek > dayOfWeek ? -1D : 1D;
do
{
date = date.AddDays(direction);
} while (date.DayOfWeek != dayOfWeek);
}
return date;
}
答案 4 :(得分:0)
找到最近的星期四的伪代码:
for 0 to 3 as x
if today + x days is Thursday
return (today + x days)
if today - x days is Thursday
return (today - x days)
本周四发现的伪代码:
lookForward = true
lookBackward = true
FirstDayOfTheWeek = Sunday
for 0 to 6 as x
if today + x days is FirstDayOfTheWeek
lookForward = false
if today - x days is FirstDayOfTheWeek
lookBackward = false
if lookForward and today + x days is Thursday
return (today + x days)
if lookBackward and today - x days is Thursday
return (today - x days)
对不起,我不会说C#:)
答案 5 :(得分:0)
// This is fixed...
int thursday = 4;
int difference = thursday - (int)DateTime.Now.DayOfWeek;
DateTime thursdayThisWeek = DateTime.Now.Date.AddDays(difference);