开发者

Last day of year same week as first day of next year

What's the easiest way to determin开发者_开发知识库e if the last day of the year falls in the same week as the first day of the next year?


It's quite easy. If the last day is not a Sunday, then then first day of the next year must be on the same week!

Depending when you start the week, of course.


var lastDay = new DateTime(2009, 12, 31);
var firstDay = new DateTime(2010, 1, 1);

bool isSameWeek = (int)lastDay.DayOfWeek < (int)firstDay.DayOfWeek;

Edit: You didn't ask this, but I think it is more interesting to calculate if two dates fall within the same week. This will also work for your question, but it also solves the problem in a much more general sense. It works by getting the calculating the start of the week for each date, then it compares if the date portions of the DateTime values are the same (just in case different times are passed in with each date).

/// <summary>
/// Determines whether two dates fall in the same week span.
/// </summary>
/// <param name="left">The left DateTime to compare.</param>
/// <param name="right">The right DateTime to compare.</param>
/// <returns>
/// </returns>
public bool IsSameWeek(DateTime left, DateTime right) {
    return AreDatePartsEqual(GetStartOfWeek(left), GetStartOfWeek(right));
}

/// <summary>
/// Gets the start of week.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
public DateTime GetStartOfWeek(DateTime date) {
    return date.AddDays(-1 * (int)date.DayOfWeek);
}

/// <summary>
/// Compares two DateTimes using only the Date Part for equality
/// </summary>
/// <param name="left">The left DateTime to compare.</param>
/// <param name="right">The right DateTime to compare.</param>
/// <returns></returns>
public bool AreDatePartsEqual(DateTime left, DateTime right) {
    return
        left.Day == right.Day &&
        left.Month == right.Month &&
        left.Year == right.Year;
}


Just create a DateTime object for December 31st. If it doesn't fall on a Saturday, then January 1st has to be within the same week.

DayOfWeek day = new DateTime(someYear, 12, 31).DayOfWeek;
if(day < DayOfWeek.Saturday)
   // January 1st must be within the same week

Edit: As Groo pointed out, the start of the week might not always be a Sunday. If it is not, then you could make it <= DayOfWeek.Saturday, or use System.Globalization.CultureInfo.DateTimeFormat.FirstDayOfWeek + 7 to find the last day of the week.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜