Find the each dates between two dates C# [duplicate] - c#

This question already has answers here:
Create an array or List of all dates between two dates [duplicate]
(4 answers)
Closed 2 years ago.
As i'm looking into possible solution to get dates between two dates. E.g. from 01-Dec-2020 to 05-Dec-2020 answer will be 02-Dec-2020,03-Dec-2020 and 04-Dec-2020.
As the solution which i get is like these below.
DateTime futurDate = Convert.ToDateTime("08/21/2016");
DateTime TodayDate = DateTime.Now;
var numberOfDays = (futurDate - TodayDate).TotalDays;
or
DateTime FutureDate = DateTime.ParseExact("08/21/2016", "mm/dd/yyyy", CultureInfo.InvariantCulture);
DateTime TodayDate = DateTime.Now;
int days = (FutureDate - TodayDate).Days;
which only gives days count.
How can i get dates in between them .. ?

We can do it with a loop for clarity.
DateTime futurDate = Convert.ToDateTime("08/21/2016");
DateTime TodayDate = DateTime.Now;
var days = (futurDate - TodayDate).Days;
var datesBetween = new List<DateTime>();
for(var i=0; i < days; i++)
{
datesBetween.Add(TodayDate.AddDays(i + 1)); //Here are your dates
}
Or with enumerables:
var datesBetween =
Enumerable.Range(1, (futurDate - TodayDate).Days)
.Select(i => TodayDate.AddDays(i));

Related

Last Day Of The month [duplicate]

This question already has answers here:
How to get last Friday of month(s) using .NET
(6 answers)
Closed 4 years ago.
I'm writing a method that returns the last saturday of the month
public static DateTime LastDayOfTheMOnth(DateTime Date)
I don't know how to start, in java is simple but in c# is more dificult
You can add a month to the current day and go backwards from there.
Taken from here.
I've made it as an extension method so that you can call it from the DateTimeobject itself.
public static DateTime LastThursday(this DateTime time)
{
DateTime date = new DateTime(time.Year, time.Month, 1).AddMonths(1).AddDays(-1);
while (date.DayOfWeek != DayOfWeek.Thursday) {
date = date.AddDays(-1);
}
return date;
}
Can be called like
DateTime x = new DateTime(2019, 4, 22);
Console.WriteLine(x.LastThursday());
First you need to get list of Saturday in specific month
var daysInMonth = DateTime.DaysInMonth(year, month);
List<DateTime> list = new List<DateTime>();
for (int day = daysInMonth; day > 0; day--)
{
DateTime currentDateTime = new DateTime(year, month, day);
if (currentDateTime.DayOfWeek == DayOfWeek.Saturday)
{
list.Add(currentDateTime);
}
}
secondly, use linq to get last Saturday from the list
var result = list.OrderByDescending(d => d.Date).First();
Console.WriteLine(result);
note: you can change DayOfWeek.Saturday to any day you want
Working example
You can use:
public static DateTime LastThursdayOfTheMonth(int month, int year)
{
DateTime date = new DateTime(year, month, DateTime.DaysInMonth(year, year));
while (date.DayOfWeek != DayOfWeek.Thursday)
{
date = date.AddDays(-1);
}
return date;
}
Regards, LA.

Getting Just date of current Week given Day name string

I need to get Date only given I have string day name, So far I have tried this
var now = DateTime.Now.Date;
var currentDay = now.DayOfWeek;
int days = (int)currentDay+1;
dt1 = now.AddDays(-days);
dt1 = dt1.AddHours(hour);
example "Tuesday". Get todays date bc today is tuesday
But no luck
base on
C#: DateTime.DayOfWeek to string comparison - Stack Overflow
c# - How can I get the DateTime for the start of the week? - Stack Overflow
DateTime getDate(string dayOfWeekString)
{
var dayOfWeek = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), dayOfWeekString);
var now = DateTime.Now.Date;
var diff = (7 + (now.DayOfWeek - dayOfWeek)) % 7;
return now.AddDays(-1 * diff).Date;
}
Console.WriteLine(getDate("Tuesday"));
Console.ReadLine();

Taking a DateTime and Comparing the Time [duplicate]

This question already has answers here:
How to Handle Actual Time with Durations in C#?
(4 answers)
Closed 4 years ago.
I have a DateTime object with DateTime stored within it.
How would I take that DateTime and compare its time so I can check whether the time within that DateTime is greater, or less than 11:00:00 or 20:00:00 etc?
TimeOfDay is what you can use;
DateTime today = DateTime.Now;
TimeSpan timeCheck = (7,0,0) //07:00
If(today.TimeOfDay > timeCheck)
{
//do something
}
or you could also use Hour that gets the hour component of the date in a way;
DateTime today = DateTime.Now;
If(today.Hour > 6)
{
//do something
}
You can try using TimeOfDay:
DateTime source = DateTime.Now;
if (source.TimeOfDay >= new TimeSpan(11, 0, 0) &&
source.TimeOfDay <= new TimeSpan(20, 0, 0)) {
...
}
Try the DateTime.CompareTo Method (DateTime).
https://msdn.microsoft.com/en-us/library/5ata5aya(v=vs.110).aspx
Here is another approach.
DateTime dt = DateTime.Now;
int[] timeOnly = Array.ConvertAll(dt.ToString("HH:mm:ss").Split(':'), int.Parse);
TimeSpan ts = new TimeSpan(timeOnly[0],timeOnly[1],timeOnly[2]);
if (ts >= new TimeSpan(11, 0, 0) && ts <= new TimeSpan(20, 0, 0)) {
Console.WriteLine("InBetween");
}
else
Console.WriteLine(dt.ToString("HH:mm:ss"));
Proof of work

Get date of last seven days

I want to get date of last seven days from now.For example current date is
02-10-2016, get date of seven days like this
01-10-2016,30-09-2016,29-09-2016,28-09-2016,27-09-2016,26-09-2016
My code
string dt = DateTime.Now.ToString("yyyy-MM-dd");
DateTime lastWeek = dt.AddDays(-7.0);
AddDays is a part of DateTime, not of string.
You need to build your dates iteratively and then convert it to a string.
DateTime[] last7Days = Enumerable.Range(0, 7)
.Select(i => DateTime.Now.Date.AddDays(-i))
.ToArray();
foreach (var day in last7Days)
Console.WriteLine($"{day:yyyy-MM-dd}"); // Any manipulations with days go here
Without LINQ, with a simple loop:
DateTime dt = DateTime.Now;
for (int i=0;i<7;i++)
{
dt = dt.AddDays(-1);
Console.WriteLine(dt.Date.ToShortDateString());
}
Try using Linq:
var date = new DateTime(2016, 10, 2);
var result = Enumerable.Range(1, 7)
.Select(day => date.Date.AddDays(- day))
.ToArray(); // if you want to represent dates as an array
Test
// 01-10-2016,30-09-2016,29-09-2016,28-09-2016,27-09-2016,26-09-2016,25-09-2016
Console.Write(string.Join(",", result.Select(d => d.ToString("dd-MM-yyyy"))));
You are almost there, the AddDays method will add only a specific number of days to the given data and dives you the resulted date. But here in your case you need a list of dates, so you have to loop through those dates and get them as well. I hope the following method will help you to do this:
public static string GetLast7DateString()
{
DateTime currentDate = DateTime.Now;
return String.Join(",",Enumerable.Range(0, 7)
.Select(x => currentDate.AddDays(-x).ToString("dd-MM-yyyy"))
.ToList());
}
Note : If you want to exclude the current date means you have to take the range from 7 and the count should be 7. You can read more about Enumerable.Range here
If you call this method like the following means you will get the output as 24-10-2016,23-10-2016,22-10-2016,21-10-2016,20-10-2016,19-10-2016,18-10-2016
string opLast7Days = GetLast7DateString();
public static List<DateTime> getLastSevenDate(DateTime currentDate)
{
List<DateTime> lastSevenDate = new List<DateTime>();
for (int i = 1; i <= 7; i++)
{
lastSevenDate.Add(currentDate.AddDays(-i));
}
return lastSevenDate;
}

How can I get a collection of months between two Dates?

Below is my code. I am only getting the difference between two dates, but I want the name of that month which comes between the from and to dates.
public static int GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
return monthDiff - 1;
}
else
{
return monthDiff;
}
}
Based on your code you could substract the month difference from the "to" DateTime to get DateTime difference from your input.
public static List<DateTime> GetMonthsBetween(DateTime from, DateTime to)
{
if (from > to) return GetMonthsBetween(to, from);
var monthDiff = Math.Abs((to.Year * 12 + (to.Month - 1)) - (from.Year * 12 + (from.Month - 1)));
if (from.AddMonths(monthDiff) > to || to.Day < from.Day)
{
monthDiff -= 1;
}
List<DateTime> results = new List<DateTime>();
for (int i = monthDiff; i >= 1; i--)
{
results.Add(to.AddMonths(-i));
}
return results;
}
To get the name of the month just format the DateTime to "MMM".
var dts = GetMonthsBetween(DateTime.Today, DateTime.Today.AddMonths(5));
foreach (var dateTime in dts)
{
Console.WriteLine(dateTime.ToString("MMM"));
}
If you want the names of all months between two dates, use something like this:
var d1 = new DateTime(2015,6,1);
var d2 = new DateTime(2015,9,1);
var monthlist = new List<string>();
string format = d1.Year == d2.Year ? "MMMM" : "MMMM yyyy";
for (var d = d1; d <= d2; d = d.AddMonths(1))
{
monthlist.Add(d.ToString(format));
}
The full list is now in monthlist - you will want to return that from your method.
Assuming you're using Java and JodaTime there are several flaws in your code.
You cant use from > to to evaluate if a date is after an other. Use from.isAfter(to) instead.
JodaTime already supplies a method to calculate the amount of whole months between two given Dates Months.monthsBetween(start,end).
With the calculated month difference you can instantiate a new DateTime object that holds a date in your desired month and output its name via yourNewDateTimeObject.month().getAsText().
edit: Just found out you're using C# so ignore my text above this. Below here I will try to answer your question in C#.
Why dont you just subtract the from from the to date and obtain your difference?
The resulting TimeSpan can be used to determine the amount of whole months between your two given dates.
To obtain the resulting month name you could use yourDateTime.ToString("MMMM");

Categories