从上周开始的日期和日期

时间:2012-04-27 10:54:21

标签: c#-4.0

我在C#.Net工作。我需要From Date和To Date。 例如:如果我选择“上周”意味着,我应该在4月15日 - 4月21日。 “2周前”是指4月8日至4月14日。与3周前,4周前等相同。

如何获取起始日期和迄今为止..

2 个答案:

答案 0 :(得分:0)

  var currentWeek_StartDate = GetStartWeekDate_By_Date(DateTime.Now.Date);

  var lastWeek_StartDate = GetStartWeekDate_By_WeekIndex(currentWeek_StartDate, -1);
  var lastWeek_EndDate = GetEndWeekDate_By_StartWeekDate(lastWeek_StartDate);


public static DateTime GetStartWeekDate_By_Date(DateTime date)
{
  return date.AddDays(-(int)date.DayOfWeek);
}
public static DateTime GetEndWeekDate_By_StartWeekDate(DateTime date)
{
  return date.AddDays(6);
}
public static DateTime GetStartWeekDate_By_WeekIndex(DateTime date, int weekIndex)
{
  return date.AddDays(weekIndex * 7);
}

答案 1 :(得分:0)

我做了一个控制台程序..工作正常..检查出来

static void Main(string[] args)
        {
            Console.WriteLine("Enter week number");
            int week = int.Parse(Console.ReadLine());
            var weekStartDay = DayOfWeek.Monday;
            int daysInAWeek = 7;
            DateTime thisWeekStarttingDate = DateTime.Now.Subtract(new TimeSpan((int)DateTime.Now.DayOfWeek - (int)weekStartDay, 0, 0, 0)).Date;

            DateTime fromDate = thisWeekStarttingDate.Subtract(new TimeSpan(daysInAWeek * week, 0, 0, 0));
            DateTime toDate = fromDate.AddDays(daysInAWeek-1);

            Console.WriteLine("from date:" + fromDate.ToShortDateString());
            Console.WriteLine("to date:" + toDate.ToShortDateString());
            Console.ReadKey();
        }