How do i check if a set time equals the system Time - c#

I'm making a little alarm clock as a project to practice as I'm just a beginner.
I got 2 textboxes in which the user can put in the hours and minutes at which he wants the alarm to go off.
How do i check if the alarm time provided by the user is the same as the time on his system / pc?

Use
int hours = System.DateTime.Now.Hour;
int minutes = System.DateTime.Now.Minute;
if(Convert.Toint32(txtHours.Text) == hours && Convert.Toint32(txtMinutes.Text) == minutes)
{
// same time
}
else
{
// time not same
}

Here is a litle sample to get you on your way
int myMinute = 5;
int myHour = 19;
if (DateTime.Now.Minute == myMinute && DateTime.Now.Hour == myHour)
{
}

All above answers are helpful but you should make in practice to use TimeSpan for comparing date or time.
int hour=5;
int min=20;
int sec=0;
TimeSpan time = new TimeSpan(hour, min, sec);
TimeSpan now = DateTime.Now.TimeOfDay;
// see if start comes before end
if (time == now)
{
//put your condition
}
Please see this url for more info.
How to check if DateTime.Now is between two given DateTimes for time part only?

var current = DateTime.Now;
if (current.Hour == 9 && current.Minute == 0) {
//It is 9:00 now
}

if(Convert.ToInt32(tbHours.Text) == DateTime.Now.Hours
&& Convert.ToInt32(tbMinutes.Text) == DateTime.Now.Minutes)
{
//set off alarm
}

Related

How to find given Event datetime is past event or Future event while considering hours aslo

I have Events page, In that displaying past present and future events counts and list. Here I'm facing a issue form QA team.
Example:
**Event date** is : 2022-01-20 08:00:00.000
**Current datetime** is: 2022-01-20 10:00:00.000
now based on above dates , we need to display event as past event because of two hours less than the Current datetime
if (planEvents.Count > 0)
{
switch (statusID)
{
case (int)GenericEnum.EventStatus.TodaysEvents:
events = planEvents.Where(o => o.EventDate.Date == DateTime.Today.Date).Skip(startIndex - 1).Take(pageSize).ToList();
totalCount = planEvents.Where(o => o.EventDate.Date == DateTime.Today.Date).ToList().Count();
break;
}
}
I tried above code but it's only returning date matching records but not hours comparison. can any once please help me.
First off, you should probably use UTC for all times, but that's a different issue. I don't really understand the use case you're after, but you can use the current time and add or subtract time units to create a range start and end. Not tested, but you should have something like this to select from a date range:
var start = DateTime.Now.AddHours(-2); // start from 2 hours ago
var end = DateTime.Now.AddHours(2); // end 2 hours from now
events = planEvents.Where(x => x.EventDate > start && x.EventDate < end);
Considering present events are the one falls within the current hour. Not tested, but it should work
if (planEvents.Any()) //Use Any method to improve performance
{
switch (statusID)
{
case (int)GenericEnum.EventStatus.TodaysEvents:
var todaysEvents = planEvents.Where(o => o.EventDate.Date == DateTime.Today.Date);
var todaysTotalEvents = todaysEvents.Count();
var currentHour = DateTime.Now.Hour;
var pastEvents = todaysEvents.Where(e=> e.EventDate.Hour < currentHour);
var presentEvents = todaysEvents.Where(e=> e.EventDate.Hour == currentHour);
var futureEvents = todaysEvents.Where(e=> e.EventDate.Hour > currentHour);
break;
}
}

How to get the last count, or the last time in a day

I have a problem finding the last time in the day (the time it's the biggest) picture below, how can I get that time?
I have to compare this time with his shift, but when I do it, I always read for the first time.
This is my code:
foreach (var shift in shifts)
{
if (von.ZPZ_Von <= shift.Arbeitsbeginn.AddMinutes(-20) &&
bis.ZPZ_Bis >= shift.Arbetsende.AddMinutes(-10))
return null;
else if (von.ZPZ_Von >= shift.Arbeitsbeginn.AddMinutes(20) &&
bis.ZPZ_Bis >= shift.Arbetsende.AddMinutes(10))
return null;
else if (von.ZPZ_Von <= shift.Arbeitsbeginn.AddMinutes(5)
&& bis.ZPZ_Bis <= shift.Arbetsende.AddMinutes(10)
)
return shift;
}
It is a method that finds the shift of workers, and if in the correct shift the worker returns the shift, if the worker comes 20 minutes or works more than 10 minutes then returns null.
This looks like data for one day:
So I need to compare the ZPZ_Bis with the last, or rather, the time.
At the moment, my method always compares ZPZ_Bis with the first departure time, i. 1899-12-30 09:52:00.000 in this case.
I would be grateful if somebody could help me with this problem, I have not really known how to handle this in the last few days.
this is my whole method:
private A_Arbeitszeitplan DetectShift(List<A_Arbeitszeitplan> shifts, PRAESENZZEIT von, PRAESENZZEIT bis, List<PRAESENZZEIT>arrivals)
If you only wish to use the TimeSpan of your DateTime you can get it like so:
From a DateTime, you can use .TimeOfDay - but that gives you a
TimeSpan representing the time into the day (10 hours).
Of course you need to compare TimeSpans with eachother:
if (von.ZPZ_Von.TimeOfDay <= shift.Arbeitsbeginn.AddMinutes(-20).TimeOfDay &&
bis.ZPZ_Bis.TimeOfDay >= shift.Arbetsende.AddMinutes(-10).TimeOfDay)
return null;

Best way to compare Periods in using NodaTime (or alternative)

I have a requirement to have a relative min/max date validation able to be stored in a database to customize an application per customer. I decided that the NodaTime.Period due to it's capability to specify years was the best choice. However, NodaTime.Period does not offer a way to compare itself against another period.
Example data provided for this validation:
Minimum Age of 18 years old.
Maximum Age o 100 years old.
Minimum sale duration of 1 month
Maximum sale duration of 3 months
Minimum advertising campaign 7 days
(Note: Current requirements are that Year / Month / Day will not be combined in validations)
The validations are:
public Period RelativeMinimum { get; set; }
public Period RelativeMaximum { get; set; }
Given a user entered date (and now):
var now = new LocalDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
var userValue = new LocalDate(date.Year, date.Month, date.Day);
var difference = Period.Between(userValue, now);
I have a comparison of:
if(RelativeMinimum != null && difference.IsLessThan(RelativeMinimum))))
{
response.IsValid = false;
response.Errors.Add(MinimumErrorMessage);
}
Which is consuming an extensions class:
public static class PeriodExtensions
{
public static bool IsLessThan(this Period p, Period p2)
{
return (p.Years < p2.Years) || (p.Years == p2.Years && p.Months < p2.Months) || (p.Years == p2.Years && p.Months == p2.Months && p.Days < p2.Days);
}
public static bool IsGreaterThan(this Period p, Period p2)
{
return (p.Years > p2.Years) || (p.Years == p2.Years && p.Months > p2.Months) || (p.Years == p2.Years && p.Months == p2.Months && p.Days > p2.Days);
}
}
While this approach works, given the test conditions I have, I have to wonder why #jon-skeet didn't implement this, and immediately have to worry over what am I missing and what alternative should I be using instead?
The main reason periods aren't comparable is that they can contain components of variable lengths.
Two one-month periods aren't necessarily the same number of days long. As an example, which is greater: 1 month or 30 days? If the month is January, then that's longer than 30 days. If the month is February, that's less than 30 days.
The same applies to years. Some are 365 days long, some are 366.
Of course, that all assumes you're using the Gregorian calendar. Noda Time supports other calendar systems, and there are similar quirks in those as well.
Regarding the code:
If you want a LocalDate from a DateTime, use LocalDateTime.FromDateTime(dt).Date
To get the current date, use SystemClock.Instance.Now.InZone(tz).Date
If you intended that to be the same as DateTime.Now, which uses the local time zone of the computer where the code is running, then get tz by calling DateTimeZoneProviders.Tzdb.GetSystemDefault()
For comparison of the type of problem you have described, consider defining min and max days instead of min and max periods. Then you wont have such variation of units. You can get the difference in days like this:
long days = Period.Between(d1, d2, PeriodUnits.Days).Days;
I believe something like this would work well for your use case:
public static bool IsDifferenceLessThan(LocalDate d1, LocalDate d2, Period p)
{
if (p.HasTimeComponent)
throw new ArgumentException("Can only compare dates.", "p");
if (p.Years != 0)
{
if (p.Months != 0 || p.Weeks != 0 || p.Days != 0)
throw new ArgumentException("Can only compare one component of a period.", "p");
var years = Period.Between(d1, d2, PeriodUnits.Years).Years;
return years < p.Years;
}
if (p.Months != 0)
{
if (p.Weeks != 0 || p.Days != 0)
throw new ArgumentException("Can only compare one component of a period.", "p");
var months = Period.Between(d1, d2, PeriodUnits.Months).Months;
return months < p.Months;
}
if (p.Weeks != 0)
{
if (p.Days != 0)
throw new ArgumentException("Can only compare one component of a period.", "p");
var weeks = Period.Between(d1, d2, PeriodUnits.Weeks).Weeks;
return weeks < p.Weeks;
}
var days = Period.Between(d1, d2, PeriodUnits.Days).Days;
return days < p.Days;
}
Just as an additional point to Matt's already-excellent answer, we provide an option for creating an IComparer<Period> with a specific anchor point, e.g.
var febComparer = Period.CreateComparer(new LocalDate(2015, 2, 1).AtMidnight());
var marchComparer = Period.CreateComparer(new LocalDate(2015, 3, 1).AtMidnight());
var oneMonth = Period.FromMonths(1);
var twentyNineDays = Period.FromDays(29);
// -1: Feb 1st + 1 month is earlier than Feb 1st + 29 days
Console.WriteLine(febComparer.Compare(oneMonth, twentyNineDays));
// 1: March 1st + 1 month is later than March 1st + 29 days
Console.WriteLine(marchComparer.Compare(oneMonth, twentyNineDays));

How to make my calculation more accurate

I work on a calculator when I try to receive precisely the amount of vacation used for one single month.
This works perfectly when I book a hole day . But if I want to a some hours or just a 1/2 it is "not working" it is displayed as a whole day.
How can I make my calculation more precise ?
public double[] GetMonthReport(int year)
{
double[] yearMonths = new double[13];
if (this.HtVacationDays.Any())
{
}
{
foreach (ZvVacationDay vacationDay in this.ZvVacationDay)
{
foreach (DateTime vacationDayDate in vacationDay.GetDates())
{
if (vacationDayDate.Year == year)
{
yearMonths[vacationDayDate.Month] += 1;
}
}
}
}
return yearMonths;
}
In my ZvVacationDay I have FromDate (datetime) and a ToDate(datetime) and also a title as varchar etc...
Here is a example for my data in the db. now for a "whole" day of vacation
FromDate 2009-08-17 08:00:00:000 ToDate 2009-08-17 16:00:00:000
Thanks for help and fast answer !
The pseudo-code would be:
if (vacationDayDate.Year == year)
{
if({isHalfDay})
yearMonths[vacationDayDate.Month] += 0.5;
else // is full day
yearMonths[vacationDayDate.Month]++;
}
Or more succinctly:
if (vacationDayDate.Year == year)
{
yearMonths[vacationDayDate.Month] += {isHalfDay} ? 0.5 : 1.0;
}
You would need to know how much time they took off.
You could either store Days off as a number of hours/part days off so your iteration becomes
foreach(TimeSpan vacationTimeOff in vacationDay.GetTimeOff())
or have a RAHalfVacationDays and iterate over that.
As soon as you have the partial days as a datasource it becomes trivial
yearMonths[vacationDayDate.Month] += timeOff;

DateTime interval restriction in C#

The problem:
I am in process of implementing a scheduler for my advisor in school. The scheduler supposes to setup a 15 minutes interval time slot from 8:00 AM to 5:00 PM, Monday to Friday. In addition, the advisor will have to specify the start and end dates of the scheduler. The scheduler will also feature an option to specify if the 15 minutes time slot is not open. Meaning my advisor will be able to mark specific time slot as NOT AVAILABLE.
What I have so far:
I have created a simple class:
public class TimeSlot
{
public DateTime dateTime
{
get;
set;
}
public bool isAvailable
{
get;
set;
}
TimeSlot(DateTime dt, bool Avalible)
{
dateTime = dt;
isAvailable = Avalible;
}
}
The class basically represents an object for one time slot in the scheduler. I also have a list of time slots that keeps a list of the valid time slots:
List<TimeSlot> TSList = new List<TimeSlot>();
Note that a valid time slot means the following:
Date is within: Monday to Friday.
Time is within: 8:00 AM to 5:00 PM
Time slots are within: 15 minutes interval.
In addition, I have a method that fill in the TSList as the following:
private void button_Next_Click(object sender, RoutedEventArgs e)
{
/* Getting the values of fromDate and toDate from the GUI controls*/
DateTime fromDate = datePicker1.SelectedDate.Value;
DateTime toDate = datePicker2.SelectedDate.Value;
while (fromDate <= toDate)
{
/*This ensures that we only deal with days Monday to Friday*/
if (fromDate.DayOfWeek.ToString() != "Saturday" && fromDate.DayOfWeek.ToString() != "Sunday")
{
/*PROBLEM HERE!!*/
}
/*Updating fromDate: Incrementing fromDate by 1 day*/
fromDate = fromDate.AddDays(1);
}
}
Notes that I was only able to satisfy the first condition in my valid time slot conditions. Thus, I was only able to restrict the dates to be within Monday to Friday range.
The questions:
I am trying to achieve the missing two valid conditions for a time slot:
How to restrict the times to be only 8:00am to 5:00 pm?
How to make time slots separated by 15 minutes interval?
First, please use DayOfWeek.Saturday and DayOfWeek.Sunday for the comparision, converting to a string is not necessary...
Then just use a simple loop like
DateTime startSlot = fromDate.Date.AddHours(8); // Starts at 8:00AM
while (startSlot.Hour < 17) {
// Construct time slot class
startSlot = startSlot.AddMinutes(15);
}
This gives you startSlot values starting at 8:00am at every date ranging to 5pm (i.e. the last one is 4:45pm).
Why are you considering building this out of nothing?
Why are you not starting with one of the many calendar management programs that are available off the shelf? For example, Microsoft Outlook contains calendar and schedule management, and you can do all of what you describe, easily. It also integrates with other scheduling tools via .ICS files, it syncs with mobile devices, syncs with Google Calendar, and so on.
But there are lots of other options. Google Calendar is another obvious one.
I don't know why you would ever consider starting from scratch. Unless it's an academic exercise (and no, I don't mean that you work in academia), then you should use larger building blocks to start.
It's like building a structure, starting with sand and water, instead of pre-fabricated concrete block.
Just quick implementation. Let me know if you need some comments.
// Round interval
const int roundInterval = 15;
var remainder = fromDate.TimeOfDay.Minutes % roundInterval;
var curTime = remainder == 0 ? fromDate : fromDate.AddMinutes(roundInterval - remainder);
curTime = curTime.AddSeconds(-curTime.TimeOfDay.Seconds);
var delta = TimeSpan.FromMinutes(roundInterval);
while (curTime < toDate)
{
while (curTime.DayOfWeek == DayOfWeek.Saturday || curTime.DayOfWeek == DayOfWeek.Sunday)
{
curTime = curTime.Date.AddDays(1);
}
if (curTime.TimeOfDay.Hours < 8)
{
curTime = curTime.AddHours(8 - curTime.TimeOfDay.Hours);
curTime = curTime.AddMinutes(-curTime.TimeOfDay.Minutes);
continue;
}
if (curTime.TimeOfDay.Hours >= 17)
{
curTime = curTime.AddHours(24 - curTime.TimeOfDay.Hours);
curTime = curTime.AddMinutes(-curTime.TimeOfDay.Minutes);
continue;
}
TSList.Add(new TimeSlot(curTime, true));
curTime = curTime.Add(delta);
}
}
DateTime myScheduledTimeSlot = new DateTime(2010, 10, 26, 8, 45, 0);
// Use existing check to check day of week constraint...
// Check if the datetime falls on a correct minute boundary
switch (myScheduledTimeSlot.Minute)
{
case 0:
case 15:
case 30:
case 45:
// The time slot is valid
break;
default:
// The time slot is not valid
break;
}
It is pretty simple to check whether it falls in a 15 minute slot as you don't have weird boundaries keeping every hour identical. I'd recommend checking out Quart.NET if you want to save some time doing eventing/scheduling.

Categories

Resources