c# - How do I loop through a time range - c#

I would like to define the start time as 6pm and end time as 9pm. This time range (something looked like below) used for everyday's schedule. How do I implement in for loop? Appreciate for any reply.
6:00 PM
6:30 PM
7:00 PM
7:30 PM
8:00 PM
8:30 PM
9:00 PM

you could use while loop
var startTime = DateTime.Parse("2012-01-28 18:00:00");
var endTime = startTime.AddHours(3);
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}

Simple example with TimeSpan:
for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
Console.WriteLine(TimeSpan.FromMinutes(minutes));
}

you can try using DateTime.Now.Hour to get the hour and use if clauses. see exemple below
if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) { Console.WriteLine("Bonjour " + Environment.UserName); }
else
{
Console.WriteLine("Bonsoir " + Environment.UserName);
}

if u r going through current date with a time range from like 10:00:00 AM to 17:00:00 PM then u could use the below code
DateTime startTime = DateTime.Parse("10:00:00");
DateTime endTime = DateTime.Parse("17:00:00");
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}

When you use TimeSpan (time instead of Time and Date in DateTime)
TimeSpan interval = new TimeSpan(0, 30, 0);
TimeSpan beginTime = new TimeSpan(18, 00, 00);
TimeSpan endTime = new TimeSpan(21, 00, 00);
for(TimeSpan tsLoop = beginTime; tsLoop < endTime; tsLoop = tsLoop.Add(interval))
{
}

Related

How to get interval between hours and put into list from start into finish?

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.

How to delete a particular time slot, from the difference between two dates

string StartDateString = "2020-04-20 18:05:07.6187";
DateTime StartDate = DateTime.Parse(StartDateString);
string EndDateString = "2020-04-22 14:10:00.6187";
DateTime EndDate = DateTime.Parse(EndDateString);
TimeSpan DifferenceStartDateEndDate = StartDate - EndDate;
Now I want to delete time between 10 pm to 8am from DifferenceStartDateEndDate (1 day 20 hours four minutes). I.e. I want to remove time between 10 pm to 8 am which will occur from StartDate to EndDate.
As I understand it, you need to add to your calculation only hours in a day during which your business is active. (08:00 - 22:00)
Here are two helpers:
// For the first day in our calculation
// Start at 08:00 if the given date has an hour component that is earlier
static TimeSpan GetTill2200(DateTime date)
{
if (date.Hour >= 22) return TimeSpan.Zero;
if (date.Hour < 8) date = date.Date.AddHours(8);
return date.Date.AddHours(22) - date;
}
// For the last day in our calculation
// End at 22:00 if the given date has an hour component that is later
static TimeSpan GetFrom0800(DateTime date)
{
if (date.Hour < 8) return TimeSpan.Zero;
if (date.Hour >= 22) date = date.Date.AddHours(22);
return date - date.Date.AddHours(8);
}
And here is the code flow to combine start and end dates and the dates in the middle
// StartDate and EndDate variables as in your question.
TimeSpan result = GetTill2200(StartDate);
DateTime currentDate = StartDate.AddDays(1);
while (currentDate.Date < EndDate.Date)
{
// Add 14 hours
// Total: 17:54:52:3813
result = result.Add(TimeSpan.FromHours(14));
currentDate = currentDate.AddDays(1);
}
// returns 06:10:00.6187
// Total = 1.00:04:53 ( 1 days, 4 minutes, 53 seconds )
result = result.Add(GetFrom0800(EndDate));
// Prints 1.00:04:53
Console.WriteLine(result);

DateTime Setting dates for next day

I have a Google API that takes date and time and sets up a event in customers calendar and the problem is I am using date time to add hours to the event when I boot time for 12pm noon For whatever reason, it will be listed in my Google Calendar for the day after at 12am.
Here is the code that sets up the date and the time:
// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock
if (ddAptAmPm.SelectedValue == "PM")
iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";
int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);
Can any one see where did I do this wrong
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
should be:
if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12)
iHour = 0;
Since 12 + 12 is 24, and today plus 24 hours is the next day.
Another way to write it:
if (iHour == 12) // 12 is **before** 1
iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
Another way you could do it is to construct a date string in a specific format (including the AM or PM designation), and then use DateTime.ParseExact to create your startDate. This way you don't have to do all the conversion from string to int, then add 12 hours if PM was specified, etc.
For example, this code would replace everything you currently have up to and including the startDate assignment:
// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text,
ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt",
CultureInfo.InvariantCulture);
You can read more about Date and Time Format Strings here.

C# subtract time (hours minutes)

Hello Everyone I have some interesting situation.
I want to count how many hours (in minutes) is from 20:00 to 01:00 AM, but i Don't know how, because what i have done is:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis)- Convert.ToDateTime(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalMinutes;
And i get result -> -1140 minutes, but I need that answer to be just 5 hours from 20:00 to 01:00.
I know that it is quite easy, but i have no idea how to do it.
you could do something like this
//Datetime(Year,month,day,hour,min,sec)
DateTime date1 = new DateTime(2012, 1, 1, 20, 0, 0);
DateTime date2 = new DateTime(2012, 1, 2, 1, 0, 0);
string minutes = (date2.Subtract(date1).TotalMinutes).ToString();
Tested and works 300 minutes (5 hours)
Use full date time strings that contain day part, to show that 01:00 AM is one day later than 20:00 - like following:
int minutes = Convert.ToDateTime("01/02/2012 01:00").Substract(Convert.ToDateTime("01/01/2012 20:00")).TotalMinutes;
You need to specify the Day, you are subracting (Today 1:00 AM) - (Today 8:00 PM)
I think you need to subract (Tommorrow 1:00 AM) - (Today 8:00 PM)
Be careful with adding one day to the endTime, because then the difference between 20:00 and 22:00 will be 26 hours instead of 2!
Just check whether the difference is positive (same day) or negative (next day)
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
// This should be 5 hours
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
int hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
// This should be 19 hours
dt = Convert.ToDateTime(pradziosLaikoLaukelis) - Convert.ToDateTime(pabaigosLaikoLaukelis);
hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
A bit of preparation of the two string variables is required before attempting data calculations
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
pabaigosLaikoLaukelis = DateTime.Today.ToString("dd/MM/yyyy") + " " + pabaigosLaikoLaukelis;
pradziosLaikoLaukelis = DateTime.Today.AddDays(-1).ToString("dd/MM/yyyy") + " " + pradziosLaikoLaukelis;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
Console.WriteLine("{0:D2}:{1:D2}", dt.Hours, dt.Minutes);
You need to add a day to the first TimeSpan and use TotalHours.
var pabaigosLaikoLaukelis = "01:00";
var pradziosLaikoLaukelis = "20:00";
var oneDayTimeSpan = new TimeSpan(1, 0, 0, 0);
TimeSpan dt = TimeSpan.Parse(pabaigosLaikoLaukelis).Add(oneDayTimeSpan) - TimeSpan.Parse(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalHours; // 5 hours
Using associative operations:
var pabaigosLaikoLaukelis = "21:00";
var pradziosLaikoLaukelis = "20:00";
var leftHours = (int)TimeSpan.Parse(pabaigosLaikoLaukelis).TotalHours;
var rightHours = (int)TimeSpan.Parse(pradziosLaikoLaukelis).TotalHours;
// Now we do a Modulus operation which will assure
// 23 > hours > 0
// Make sure to check that leftHours != 0 or rightHours != 0
int hours = (Math.Abs(leftHours * rightHours) + leftHours) % rightHours; //Modulus
var hoursTimeSpan = TimeSpan.FromHours(hours);
How about this:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan startTime = Convert.ToDateTime(pradziosLaikoLaukelis).TimeOfDay;
TimeSpan endTime = Convert.ToDateTime(pabaigosLaikoLaukelis).TimeOfDay;
TimeSpan diff = endTime > startTime ? endTime - startTime : endTime - startTime + TimeSpan.FromDays(1);
int minutes = (int)diff.TotalMinutes;

Compare if DateTime values are "between" specific hours

How to compare current time with another time..
System.DateTime.Now.Hour
This is for get cuurent hour.
What I want is if the time is in between
7 AM to 02:59 PM //Do something
03:00 PM to 10:59 PM //Do something
11:00 PM to 06:59 AM //Do something
Please give me any ideas..?
You may use DateTime.TimeOfDay property to compare the time with the current time.
TimeSpan startTime = new TimeSpan(7,0,0);
TimeSpan endTime = new TimeSpan(2, 59, 0);
if (DateTime.Now.TimeOfDay >= startTime &&
DateTime.Now.TimeOfDay <= endTime)
{
//in range
}
else
{
//not in range.
}
You can actually do arithmetic operations on DateTime, and it returns a timespan.
DateTime d1 = new DateTime(2012, 12, 12, 5, 5, 5);
DateTime d2 = DateTime.Now;
TimeSpan ts = new TimeSpan();
ts = d2 - d1;

Categories

Resources