Finding Week, using current date ? In C#? - c#

In C# how can i find the week of the current date, i am trying to get the week number of the current date, can you help me, thank you.

See Calendar.GetWeekOfYear
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime date1 = new DateTime(2011, 1, 1);
Calendar cal = dfi.Calendar;
Console.WriteLine("{0:d}: Week {1} ({2})", date1,
cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek),
cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));
}
}
// The example displays the following output:
// 1/1/2011: Week 1 (GregorianCalendar)

If you need current week "global" number, you can use this:
using System;
using System.Globalization;
DateTime date = DateTime.Now;
int res = 0;
// First day of year
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
// (Default) First four day week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);
// First four day week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
// First full week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);
// First full week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);
If you need week number in a month, use smth like such code:
DateTime beginningOfMonth = DateTime.Now;
while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
date = date.AddDays(1);
int result = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;

Related

Get all the dates of current week

Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?
For example, current date is 30th March 2017, the output I need is,
26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
You can try DateTimeFormat to find out current week's starting date and Linq to generate the string:
DateTime startOfWeek = DateTime.Today.AddDays(
(int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek -
(int) DateTime.Today.DayOfWeek);
string result = string.Join("," + Environment.NewLine, Enumerable
.Range(0, 7)
.Select(i => startOfWeek
.AddDays(i)
.ToString("dd-MMMM-yyyy")));
In case of en-US culture you'll get (week starts from Sunday)
26-March-2017, // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
In case of, say, ru-RU culture you'll get (week starts from Monday)
27-марта-2017, // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017
Assuming that Sunday will be the start day of the week, as it is mentioned in the question I suggest following solution.
var today = DateTime.Now.Date; // This can be any date.
Console.WriteLine(today.DayOfWeek);
var day = (int)today.DayOfWeek; //Number of the day in week. (0 - Sunday, 1 - Monday... and so On)
Console.WriteLine(day);
const int totalDaysOfWeek = 7; // Number of days in a week stays constant.
for (var i = -day; i < -day + totalDaysOfWeek; i++)
{
Console.WriteLine(today.AddDays(i).Date);
}
I found this here
DayOfWeek Day = DateTime.Now.DayOfWeek;
int Days = Day - DayOfWeek.Monday; //here you can set your Week Start Day
DateTime WeekStartDate = DateTime.Now.AddDays(-Days);
DateTime WeekEndDate1 = WeekStartDate.AddDays(1);
DateTime WeekEndDate2 = WeekStartDate.AddDays(2);
DateTime WeekEndDate3 = WeekStartDate.AddDays(3);
DateTime WeekEndDate4 = WeekStartDate.AddDays(4);
DateTime WeekEndDate5 = WeekStartDate.AddDays(5);
DateTime WeekEndDate6 = WeekStartDate.AddDays(6);
In my opinion, an extension method is the most useful approach:
public static IEnumerable<DateTime> GetDatesOfWeek(this DateTime date, CultureInfo ci) {
Int32 firstDayOfWeek = (Int32) ci.DateTimeFormat.FirstDayOfWeek;
Int32 dayOfWeek = (Int32) date.DayOfWeek;
DateTime startOfWeek = date.AddDays(firstDayOfWeek - dayOfWeek);
var valuesDaysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast<Int32>();
return valuesDaysOfWeek.Select(v => startOfWeek.AddDays(v));
}
Use as follows:
DateTime myDate = DateTime.Today;
IEnumerable<DateTime> result = myDate.GetDatesOfWeek(CultureInfo.CurrentCulture);
foreach ( DateTime d in result ) {
Console.WriteLine(d);
}

How to find the remains date of a month from a date?

I have a date '2015-01-25'. How to get the remains date of Jan 2015. Is there any built in function to achieve this in c#
remains days ie, '2015-01-26','2015-01-27','2015-01-28','2015-01-29','2015-01-30','2015-01-31' etc..
Get Today
var today = DateTime.Now;
Get the first day of next month
var firstDayNextMonth = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1);
Create a list of the days between today and first day of next month (Enumerable.Range) Loop through the list and turn them into dates (Select) by adding each int to today
var dates = Enumerable.Range(0, firstDayNextMonth.Subtract(today).Days + 1)
.Select(d => today.AddDays(d))
.ToList();
If you want to find remaining days till next month, then you can add a day to the current DateTime in loop and check if the month of the new DateTime is same with yours. If the new DateTime met the condition, then add it to the list. If not, then break the loop.
You will use DateTime.AddDays() method which returns a new DateTime that adds the specified number of days to the value of this instance.
DateTime myDateTime = new DateTime(2015, 1, 25);
var remainedDateTimesToNextMonth = new List<DateTime>();
var nextDay = myDateTime;
while(true)
{
nextDay = nextDay.AddDays(1);
if (nextDay.Month == myDateTime.Month)
{
remainedDateTimesToNextMonth.Add(nextDay);
}
else break;
}
And int the result there would be six item inside remainedDateTimesToNextMonth list:
2015-01-26,2015-01-27,2015-01-28,2015-01-29,2015-01-30,2015-01-31
You can use DateTime.DaysInMonth(year, month) to get total days in months, and subtract the current day of month.
DateTime someDate = new DateTime(2015,1,25);
var remaining = DateTime.DaysInMonth(2015, 1) - someDate.Day;
Then you know the amount of remaining days for that given month, and can set up remaining dates in a list using an for loop.
List<DateTime> remainingDays = new List<DateTime>();
for (int i = 1; i <= remaining; i++)
{
remainingDays.Add(someDate.AddDays(i));
}

How do I determine if a date lies between current week dates?

In C#,
How we are check certain date with in week dates?
Eg: 6/02/2014
Current Weeks: 02/02/2014 - 08/02/2014
so this dates are with in above week....
Use this for check (last parameter is optional if you want always 1 week from fromDate, you don't need use last parameter):
public static bool DateInside(DateTime checkDate,
DateTime fromDate, DateTime? lastDate = null)
{
DateTime toDate = lastDate != null ? lastDate.Value : fromDate.AddDays(6d);
return checkDate >= fromDate && checkDate <= toDate;
}
To call use:
bool isDateInside = DateInside(new DateTime(2014, 02, 06),
new DateTime(2014, 02, 02)); // return true
And search first :) Answer is also here: How to check whether C# DateTime is within a range
If you want to check if the dates are inside the same week, then you can use this:
public static bool DateInsideOneWeek(DateTime checkDate, DateTime referenceDate)
{
// get first day of week from your actual culture info,
DayOfWeek firstWeekDay = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
// or you can set exactly what you want: firstWeekDay = DayOfWeek.Monday;
// calculate first day of week from your reference date
DateTime startDateOfWeek = referenceDate;
while(startDateOfWeek.DayOfWeek != firstWeekDay)
{ startDateOfWeek = startDateOfWeek.AddDays(-1d); }
// fist day of week is find, then find last day of reference week
DateTime endDateOfWeek = startDateOfWeek.AddDays(6d);
// and check if checkDate is inside this period
return checkDate >= startDateOfWeek && checkDate <= endDateOfWeek;
}
Actual week in my culture info start with monday, February 3th 2014 (so for me is week between February 3th and February 9th). If I check any date with reference date (second parameter) as today (2014-Feb-06) I get this results:
For 2014-Feb-02 (Sunday before this week): false
For 2014-Feb-03 (Monday inside this week): true
For 2014-Feb-06 (Today inside this week): true
For 2014-Feb-09 (Sunday inside this week): true
For 2014-Feb-10 (Monday next week): false
You can call this method to check if one date is inside the same week as referentional like this:
DateInsideOneWeek(new DateTime(2014, 02, 02), new DateTime(2014, 02, 06));
You can find current week start and end dates with this code:
DateTime startDateOfWeek = DateTime.Now.Date; // start with actual date
while(startDateOfWeek.DayOfWeek != DayOfWeek.Monday) // set first day of week in your country
{ startDateOfWeek = startDateOfWeek.AddDays(-1d); } // after this while loop you get first day of actual week
DateTime endDateOfWeek = startDateOfWeek.AddDays(6d); // you just find last week day
Is this you wanted?
hmm
public bool isBetween(DateTime input, DateTime date1, DateTime date2)
{
if (input > date1 && input < date2)
return true;
else
return false;
}
?
input= your date
date1 & date2 = start and end of a week
How about:
bool inRange = (date >= lowerDate && date <= upperDate);
Here's another solution :)
public static class DateExtensions
{
private static void Swap<T>(ref T one, ref T two)
{
var temp = one;
one = two;
two = temp;
}
public static bool IsFromSameWeek(this DateTime first, DateTime second, DayOfWeek firstDayOfWeek = DayOfWeek.Monday)
{
// sort dates
if (first > second)
{
Swap(ref first, ref second);
}
var daysDiff = (second - first).TotalDays;
if (daysDiff >= 7)
{
return false;
}
const int TotalDaysInWeek = 7;
var adjustedDayOfWeekFirst = (int)first.DayOfWeek + (first.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);
var adjustedDayOfWeekSecond = (int)second.DayOfWeek + (second.DayOfWeek < firstDayOfWeek ? TotalDaysInWeek : 0);
return adjustedDayOfWeekSecond >= adjustedDayOfWeekFirst;
}
}
Upd: it appears to have at least twice better performance than #Atiris solution :)

How to get All Dates in a given month in C#

I want to make a function that take month and year and return List<DateTime> filled with all dates in this month.
any help will be appreciated
Thanks in Advance
Here's a solution with LINQ:
public static List<DateTime> GetDates(int year, int month)
{
return Enumerable.Range(1, DateTime.DaysInMonth(year, month)) // Days: 1, 2 ... 31 etc.
.Select(day => new DateTime(year, month, day)) // Map each day to a date
.ToList(); // Load dates into a list
}
And one with a for-loop:
public static List<DateTime> GetDates(int year, int month)
{
var dates = new List<DateTime>();
// Loop from the first day of the month until we hit the next month, moving forward a day at a time
for (var date = new DateTime(year, month, 1); date.Month == month; date = date.AddDays(1))
{
dates.Add(date);
}
return dates;
}
You might want to consider returning a streaming sequence of dates instead of List<DateTime>, letting the caller decide whether to load the dates into a list or array / post-process them / partially iterate them etc. For the LINQ version, you can accomplish this by removing the call to ToList(). For the for-loop, you would want to implement an iterator. In both cases, the return-type would have to be changed to IEnumerable<DateTime>.
Sample for pre-Linq Framework versions, using February 1999.
int year = 1999;
int month = 2;
List<DateTime> list = new List<DateTime>();
DateTime date = new DateTime(year, month, 1);
do
{
list.Add(date);
date = date.AddDays(1);
while (date.Month == month);
I am sure there might be better ways to do this. But, you could use this:
public List<DateTime> getAllDates(int year, int month)
{
var ret = new List<DateTime>();
for (int i=1; i<=DateTime.DaysInMonth(year,month); i++) {
ret.Add(new DateTime(year, month, i));
}
return ret;
}
Here you go:
public List<DateTime> AllDatesInAMonth(int month, int year)
{
var firstOftargetMonth = new DateTime(year, month, 1);
var firstOfNextMonth = firstOftargetMonth.AddMonths(1);
var allDates = new List<DateTime>();
for (DateTime date = firstOftargetMonth; date < firstOfNextMonth; date = date.AddDays(1) )
{
allDates.Add(date);
}
return allDates;
}
Iterates through the dates from the first of the month you want through to the last date that's less than the first of the next month.
PS: If this is homework, please tag it with "homework"!

Get the previous month's first and last day dates in c#

I can't think of an easy one or two liner that would get the previous months first day and last day.
I am LINQ-ifying a survey web app, and they squeezed a new requirement in.
The survey must include all of the service requests for the previous month. So if it is April 15th, I need all of Marches request ids.
var RequestIds = (from r in rdc.request
where r.dteCreated >= LastMonthsFirstDate &&
r.dteCreated <= LastMonthsLastDate
select r.intRequestId);
I just can't think of the dates easily without a switch. Unless I'm blind and overlooking an internal method of doing it.
var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);
var first = month.AddMonths(-1);
var last = month.AddDays(-1);
In-line them if you really need one or two lines.
The way I've done this in the past is first get the first day of this month
dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
Then subtract a day to get end of last month
dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);
Then subtract a month to get first day of previous month
dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);
using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime
var lastMonth = 1.Months().Ago().Date;
var firstDayOfMonth = lastMonth.FirstDayOfMonth();
var lastDayOfMonth = lastMonth.LastDayOfMonth();
DateTime LastMonthLastDate = DateTime.Today.AddDays(0 - DateTime.Today.Day);
DateTime LastMonthFirstDate = LastMonthLastDate.AddDays(1 - LastMonthLastDate.Day);
I use this simple one-liner:
public static DateTime GetLastDayOfPreviousMonth(this DateTime date)
{
return date.AddDays(-date.Day);
}
Be aware, that it retains the time.
An approach using extension methods:
class Program
{
static void Main(string[] args)
{
DateTime t = DateTime.Now;
DateTime p = t.PreviousMonthFirstDay();
Console.WriteLine( p.ToShortDateString() );
p = t.PreviousMonthLastDay();
Console.WriteLine( p.ToShortDateString() );
Console.ReadKey();
}
}
public static class Helpers
{
public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
{
DateTime d = currentDate.PreviousMonthLastDay();
return new DateTime( d.Year, d.Month, 1 );
}
public static DateTime PreviousMonthLastDay( this DateTime currentDate )
{
return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
}
}
See this link
http://www.codeplex.com/fluentdatetime
for some inspired DateTime extensions.
The canonical use case in e-commerce is credit card expiration dates, MM/yy. Subtract one second instead of one day. Otherwise the card will appear expired for the entire last day of the expiration month.
DateTime expiration = DateTime.Parse("07/2013");
DateTime endOfTheMonthExpiration = new DateTime(
expiration.Year, expiration.Month, 1).AddMonths(1).AddSeconds(-1);
If there's any chance that your datetimes aren't strict calendar dates, you should consider using enddate exclusion comparisons...
This will prevent you from missing any requests created during the date of Jan 31.
DateTime now = DateTime.Now;
DateTime thisMonth = new DateTime(now.Year, now.Month, 1);
DateTime lastMonth = thisMonth.AddMonths(-1);
var RequestIds = rdc.request
.Where(r => lastMonth <= r.dteCreated)
.Where(r => r.dteCreated < thisMonth)
.Select(r => r.intRequestId);
DateTime now = DateTime.Now;
int prevMonth = now.AddMonths(-1).Month;
int year = now.AddMonths(-1).Year;
int daysInPrevMonth = DateTime.DaysInMonth(year, prevMonth);
DateTime firstDayPrevMonth = new DateTime(year, prevMonth, 1);
DateTime lastDayPrevMonth = new DateTime(year, prevMonth, daysInPrevMonth);
Console.WriteLine("{0} {1}", firstDayPrevMonth.ToShortDateString(),
lastDayPrevMonth.ToShortDateString());
This is a take on Mike W's answer:
internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
if (returnLastDayOfMonth) return lastDayOfLastMonth;
return firstDayOfThisMonth.AddMonths(-1);
}
You can call it like so:
dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);
var lastMonth = DateTime.Today.AddMonths(-1);
dRet1 = new DateTime(lastMonth.Year, lastMonth.Month, 1);
dRet2 = new DateTime(lastMonth.Year, lastMonth.Month, DateTime.DaysInMonth(lastMonth.Year, lastMonth.Month));

Categories

Resources