In this article, we will learn how to get the first and last day of the current week using a specific date in C#.
In .NET Framework, a DateTime class has no property or method to find the first and last day of the current week using a specific date. So we are going to use this trick to find the first and last day of the current week.
using System;
namespace Tutorialsrack
{
class Program
{
/*How to get First and Last day of the Current Week using specific date using C#*/
static void Main(string[] args)
{
//initialize a datetime variable
DateTime date = DateTime.Today;
//Returns and Print First Day of Current Week
Console.WriteLine("First Day of the Week is: {0}", datetimeext.GetFirstDayOfWeek(date).ToString("dd-MM-yyyy"));
//Returns and Print Last Day of Current Week
Console.WriteLine("Last Day of the Week is: {0}", datetimeext.GetLasttDayOfWeek(date).ToString("dd-MM-yyyy"));
Console.ReadKey();
}
}
static class datetimeext
{
//To Get The First Day of the Week in C#
public static DateTime GetFirstDayOfWeek(this DateTime date)
{
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var diff = date.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
diff += 7;
return date.AddDays(-diff).Date;
}
//To Get The Last Day of the Week in C#
public static DateTime GetLasttDayOfWeek(this DateTime date)
{
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var diff = date.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
diff += 7;
DateTime start = date.AddDays(-diff).Date;
return start.AddDays(6).Date;
}
}
}
First Day of the Week is: 14-10-2019
Last Day of the Week is: 20-10-2019
I hope this article will help you to understand how to find the First and Last day of the current week of a given date in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!.
Comments