Related
I am trying to set my DateTime start variable to change based on what time it is now. my shifts(different start times) are 1: 6am-2pm 2: 2pm-10pm 3: 10pm-6am. I am having trouble writing the if statement to give the correct time.
The short version. I am trying to write C# if statement to figure out which of the the three start it is currently. Below is the code. above is the start times.
The logic I am trying to achieve is to have the DateTime start variable to be set to one of the 3 date time I have listed. Morning, Afternoon, or Evening. The start variable needs to be change values based on DateTime.Now. The View will be refreshing the page every 15 seconds. That will update the DateTime.Now variable.
Thank you for your time.
DateTime MORNING;
DateTime AFTERNOON;
DateTime EVENING;
if (DateTime.Now.Hour > 6 || (DateTime.Now.Hour == 6 && DateTime.Now.Minute >= 00))
MORNING = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 6, 00, 0);
else
MORNING = new DateTime(DateTime.Now.AddDays(-1).Year, DateTime.Now.AddDays(-1).Month, DateTime.Now.AddDays(-1).Day, 6, 30, 0);
if (DateTime.Now.Hour > 14 || (DateTime.Now.Hour == 14 && DateTime.Now.Minute >= 00))
AFTERNOON = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 14, 00, 0);
else
AFTERNOON = new DateTime(DateTime.Now.AddDays(-1).Year, DateTime.Now.AddDays(-1).Month, DateTime.Now.AddDays(-1).Day, 14, 00, 0);
if (DateTime.Now.Hour > 20 || (DateTime.Now.Hour == 20 && DateTime.Now.Minute >= 00))
EVENING = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 20, 00, 0);
else
EVENING = new DateTime(DateTime.Now.AddDays(-1).Year, DateTime.Now.AddDays(-1).Month, DateTime.Now.AddDays(-1).Day, 20, 00, 0);
DateTime start = ((EVENING > MORNING) ? EVENING : MORNING);
DateTime end = start.AddHours(8);
I'm not sure whether you need the MORNING, AFTERNOON, or EVENING variables elsewhere in your code, but they are not needed for this; I would remove them from my sample unless you need them in other locations. If you do need those variables, you can replace my start sets to new DateTime objects with the appropriate variable, but I wanted to demonstrate that the extra variables are not at all required for this. The following should work:
DateTime now = DateTime.Now;
DateTime MORNING = new DateTime(now.Year, now.Month, now.Day, 6, 0, 0);
DateTime AFTERNOON = MORNING.AddHours(8);
DateTime EVENING = AFTERNOON.AddHours(8);
DateTime start;
// Note that hour 22 is 10PM, not hour 20 as in your example
if (now.Hour >= 22 || now.Hour < 6)
{
// Evening
start = new DateTime(now.Year, now.Month, now.Day, 22, 0, 0);
AFTERNOON -= TimeSpan.FromDays(1);
MORNING -= TimeSpan.FromDays(1);
}
else if (now.Hour >= 14)
{
// Afternoon
start = new DateTime(now.Year, now.Month, now.Day, 14, 0, 0);
EVENING -= TimeSpan.FromDays(1);
MORNING -= TimeSpan.FromDays(1);
}
else
{
// Morning
start = new DateTime(now.Year, now.Month, now.Day, 6, 0, 0);
EVENING -= TimeSpan.FromDays(1);
AFTERNOON -= TimeSpan.FromDays(1);
}
DateTime end = start.AddHours(8);
For example, I will be given a time on hours with type DateTime hours like this
for the starter
my starttime is 00:00
endtime is 02:00
and every time 30 minutes I like to input the value into a List<DateTime>
so, how can I get the value to put into a list that is look like this?
00:00
00:30
01:00
01:30
02:00
My Code
DateTime starTime = new DateTime();
DateTime endTimes = new DateTime();
DateTime interval = new DateTime();
List<DateTime> intervals = new List<DateTime>();
starTime = DateTime.ParseExact(fulldate + "00:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture);
endTimes = DateTime.ParseExact(fulldate + "02:00",
"yyyy/MM/dd HH:mm",
CultureInfo.InvariantCulture); ;
interval = starTime;
for (int i = 0; i < 24; i++)
{
interval.AddHours(0.5);
intervals.Add(interval);
if (interval.ToString("HH:mm") == endTimes.ToString("HH:mm"))
{
break;
}
}
Can anyone help me to solve this?
With some assumption (that end time is on the same day, that your end time is always something that can be devided by 30 mins, ...) this would work.
var start = new TimeSpan(0, 0, 0);
var end = new TimeSpan(2, 0, 0);
var current = start;
List<DateTime> values = new List<DateTime>();
var startDate = DateTime.Now.Date; // editited after #pinkflowydx33's comment
values.Add(startDate + start);
while (current < end)
{
current = current.Add(new TimeSpan(0, 30, 0));
values.Add(startDate + current);
}
foreach (var v in values)
{
Console.WriteLine(v);
}
i prepared that type of solution. - It's loop over number, which represent - times of valueToChange - in this specific case between 30 minutes - and add to the startDate - 30 minutes and also saving to list.
using System;
public class Program
{
public static void Main()
{
List<DateTime> intervals = new List<DateTime>();
var changeValue = 30;
var startDate = new DateTime(2010, 05, 12, 13, 00, 00);
var endDate = new DateTime(2010, 05, 12, 14, 00, 00);
var timeIntervals = System.Math.Abs(startDate.Subtract(endDate).TotalMinutes / changeValue);
for (int i = 0; i < timeIntervals; i++)
{
startDate.AddMinutes(30);
intervals.Add(startDate)
}
}
}
In this case the start and end date are divided by 30 minutes without rest - so if there will be 13:00 and 13:12 - it's doesn't add the value to List - cause the value doesn't > 30.
For my app I need to know if Now() is between two values.
The user can set a start- and an end-time so he will not disturbed by a notification (during the night for example).
So if have got two TimePickers (start- and end-time) that the user can set.
Lets say the user sets 22:00 for the StartTime and 07:00 for the EndTime (this would cover the night).
How can I check if the DateTime.Now is between the selected Start and End time?
EDIT:
I only want this to work with the Hour and minutes part. So if the user sets the Start and End time this should work for every night.
First you need to convert everything to the same units (we'll use TimeSpan), then you need to see whether the start-end times cross midnight, and finally do your comparison based on the results of that check:
// convert everything to TimeSpan
TimeSpan start = new TimeSpan(22, 0, 0);
TimeSpan end = new TimeSpan(07, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
// see if start comes before end
if (start < end)
return start <= now && now <= end;
// start is after end, so do the inverse comparison
return !(end < now && now < start);
Here's a function to do it for you:
bool TimeBetween(DateTime datetime, TimeSpan start, TimeSpan end)
{
// convert datetime to a TimeSpan
TimeSpan now = datetime.TimeOfDay;
// see if start comes before end
if (start < end)
return start <= now && now <= end;
// start is after end, so do the inverse comparison
return !(end < now && now < start);
}
You would call it like:
bool silenceAlarm = TimeBetween(DateTime.Now, StartTime.Value, EndTime.Value);
Since you are only gathering two times without dates, you need to figure out if the two times are from the same day or not. If you put the StartTime, EndTime, and Now into TimeSpans:
if (StartTime > EndTime)
{
// the range crosses midnight, do the comparisons independently
return (StartTime < Now) || (Now < EndTime);
}
else
{
// the range is on the same day, both comparisons must be true
return StartTime < Now && Now < EndTime;
}
public static bool isCurrenctDateBetween(DateTime fromDate, DateTime toDate)
{
DateTime curent = DateTime.Now.Date;
if (fromDate.CompareTo(toDate) >= 1)
{
MessageBox.Show("From Date shouldn't be grater than To Date", "DateRange",MessageBoxButton.OKCancel, MessageBoxImage.Warning);
}
int cd_fd = curent.CompareTo(fromDate);
int cd_td = curent.CompareTo(toDate);
if (cd_fd == 0 || cd_td == 0)
{
return true;
}
if (cd_fd >= 1 && cd_td <= -1)
{
return true;
}
return false;
}
DateTime nowDate = DateTime.Now;
// set these to today + time from time picker
DateTime startDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day,
selectedStart.Hour, selectedStart.Minute, 0);
DateTime endDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day,
selectedEnd.Hour, selectedEnd.Minute, 0);
bool isBetween = nowDate < endDate && nowDate > startDate;
Update 08-Jun-2016
Not sure why the downvote was appropriate as this is a working solution. The OP did ask specifically for DateTime, however I do recommend using TimeSpan instead as per the answer by #Gabe.
Here's a working function as per my answer:
public static bool TimeBetween(DateTime check, DateTime start, DateTime end, bool inclusive = true)
{
var from = new DateTime(check.Year, check.Month, check.Day,
start.Hour, start.Minute, start.Second, start.Millisecond);
var to = new DateTime(check.Year, check.Month, check.Day,
end.Hour, end.Minute, end.Second, end.Millisecond);
if (inclusive)
return from <= check && to >= check;
return from < check && to > check;
}
Here's a working fiddle: https://dotnetfiddle.net/vZCXqv.
Full code:
using System;
public class Program
{
public static void Main()
{
var start = new DateTime(1, 1, 1, 9, 0, 0);
var end = new DateTime(1, 1, 1, 17, 0, 0);
Console.WriteLine("{0} - Too early", TimeBetween(new DateTime(2014, 1, 1, 08, 59, 59, 999), start, end));
Console.WriteLine("{0} - On start time exclusive", TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 000), start, end, false));
Console.WriteLine("{0} - On start time inclusive", TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 000), start, end));
Console.WriteLine("{0} - After start time", TimeBetween(new DateTime(2014, 1, 1, 09, 00, 00, 001), start, end));
Console.WriteLine("{0} - Before end time", TimeBetween(new DateTime(2014, 1, 1, 16, 59, 59, 999), start, end));
Console.WriteLine("{0} - On end time inclusive", TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 000), start, end));
Console.WriteLine("{0} - On end time exclusive", TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 000), start, end, false));
Console.WriteLine("{0} - Too late", TimeBetween(new DateTime(2014, 1, 1, 17, 00, 00, 001), start, end));
}
public static bool TimeBetween(DateTime check, DateTime start, DateTime end, bool inclusive = true)
{
var from = new DateTime(check.Year, check.Month, check.Day, start.Hour, start.Minute, start.Second, start.Millisecond);
var to = new DateTime(check.Year, check.Month, check.Day, end.Hour, end.Minute, end.Second, end.Millisecond);
if (inclusive)
return from <= check && to >= check;
return from < check && to > check;
}
}
Just do straight comparison.
if(date > startdate && date < enddate)
Dupe of Find if current time falls in a time range
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0));
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0));
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
Timespan, again, taken from dupe.
TimeSpan start = new TimeSpan(10, 0, 0);
TimeSpan end = new TimeSpan(12, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))
{
//match found
}
I use this, so you can pass DateTime directly:
public static bool TimeBetween(DateTime time, DateTime startDateTime, DateTime endDateTime)
{
// get TimeSpan
TimeSpan start = new TimeSpan(startDateTime.Hour, startDateTime.Minute, 0);
TimeSpan end = new TimeSpan(endDateTime.Hour, endDateTime.Minute, 0);
// convert datetime to a TimeSpan
TimeSpan now = time.TimeOfDay;
// see if start comes before end
if (start < end)
return start <= now && now <= end;
// start is after end, so do the inverse comparison
return !(end < now && now < start);
}
How to get All Days between given two Dates, given "Day Name"?
Ex: Start_Date = Jan 1, 2011
End_Date = Jan 20, 2011
Day Name = Sunday
Here we need to get all Dates with dayname as "SUNDAY"
Ex:
Jan 02, 2011
Jan 09, 2011
Jan 16, 2011
I like to use Enumerable.Range for tasks like that:
DateTime start = new DateTime(2011,1,1);
DateTime end = new DateTime(2011,1,20);
var datesThatAreSundays = Enumerable
.Range(start.DayOfYear, end.Subtract(start).Days + 1)
.Select(n => start.AddDays(n - start.DayOfYear))
.Where(d => d.DayOfWeek == DayOfWeek.Sunday);
DateTime startDate = new DateTime(2011, 1, 1);
DateTime endDate = new DateTime(2011, 1, 20);
while (startDate < endDate)
{
if (startDate.DayOfWeek == DayOfWeek.Sunday)
{
// Do something
}
startDate = startDate.AddDays(1);
}
How about something like
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
if (runDate.DayOfWeek.ToString().ToLower() == dayName)
list.Add(runDate);
}
or even using Enum.TryParse
DateTime startDate = new DateTime(2011, 01, 01);
DateTime endDate = new DateTime(2011, 01, 20);
string dayName = "sunday";
DayOfWeek dow;
Enum.TryParse(dayName, true, out dow);
List<DateTime> list = new List<DateTime>();
for (DateTime runDate = startDate; runDate <= endDate; runDate = runDate.AddDays(1))
{
if (runDate.DayOfWeek == dow)
list.Add(runDate);
}
Without having tested:
DateTime start = x;
DateTime end = y;
while (start.DayOfWeek != z)
start = start.AddDays(1);
while (start <= end)
{
//DoStuff
start = start.AddDays(7);
}
You may try this
var firstDate = new DateTime(2011, 1, 1);
var lastDate = new DateTime(2011, 1, 20);
var result = (from el in Enumerable.Range(0, (lastDate - firstDate).Days)
let date = firstDate.AddDays(el)
where date.DayOfWeek == DayOfWeek.Sunday
select date).ToArray();
having a DateTime variable, for example:
DateTime testDate = new DateTime(2011,12,15,00,00,00);
how can I implement a foreach loop for every hour of this day?
Something like:
foreach (int myHour in testDate.Date)
{
}
but in this way does not compile.
It is not a good idea to loop 24, because this will not work on days with 25 or 23 hours (time change, daylight saving...).
Use the AddHour function and a target date.
DateTime testDate = new DateTime(2011, 12, 15, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
while (testDate.Date != endDate.Date)
{
Console.WriteLine(testDate.ToString());
testDate = testDate.AddHours(1);
}
More Information
MSDN - DateTimeKind Enumeration
Use for instead:
DateTime date = new DateTime(2011,12,15);
for(int i = 0; i < 24; i++)
{
DateTime time = date.AddHours(i);
...
}
If you really want to use foreach, you could create an extension method like this:
static class DateTimeExtensions
{
public static IEnumerable<DateTime> GetHours(this DateTime date)
{
date = date.Date; // truncate hours
for(int i = 0; i < 24; i++)
{
yield return date.AddHours(i);
}
}
}
...
DateTime date = new DateTime(2011,12,15);
foreach (DateTime time in date.GetHours())
{
...
}
For those who don't like plain old for loops :) :
DateTime testDate = new DateTime(2011,12,15,00,00,00);
foreach (int hour in Enumerable.Range(0,24)) {
DateTime dateWithHour = testDate.AddHours(hour);
}
foreach loop works in list but here testDate.Date never gives you hour. so in substitution of it use for loop or do while or while loop.
The code below allows you to cycle through the hours of the day but also starting from a specific hour. It could be simpler if you do not need to support starting from an hour offset.
DateTime testDate = new DateTime(2011,12,15,13,00,00);
var hoursLeft = 24 - testDate.Hour;
for (var hour = 1; hour < hoursLeft; hour++)
{
var nextDate = testDate.AddHours(hour);
Console.WriteLine(nextDate);
}
To get the hours in DLS time use this:
DateTime testDate = new DateTime(2017, 03, 26, 00, 00, 00, DateTimeKind.Local);
DateTime endDate = testDate.AddDays(1);
//these dates also contain time!
var start = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).Start;
var end = TimeZone.CurrentTimeZone.GetDaylightChanges(testDate.Year).End;
var hoursInDay = new List<DateTime>();
while (testDate.Date != endDate.Date)
{
if (start == testDate)
{
//this day have 23 hours, and should skip this hour.
testDate = testDate.AddHours(1);
continue;
}
hoursInDay.Add(testDate);
if (end == testDate)
{
hoursInDay.Add(testDate); //this day has 25 hours. add this extra hour
}
testDate = testDate.AddHours(1);
}
I'm in Denmark, so when I run this it has only 23 hours.
Iterate over all 24 hours of the day:
DateTime testDate = new DateTime(2011, 12, 15);
for (int i = 0; i < 24; i++)
{
DateTime hour = testDate.Date.AddHours(i);
// Your code here
}
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
for ( var i = today; i <= tomorrow; i = i.AddHours(1))
{
// your code
}
simply do this
DateTime testDate = new DateTime(2011, 12, 15, 10, 00, 00);
for (int i = testDate.Hour; i < 24; i++)
{
//do what ever
}