I am trying to create an if statement based on the dropdown created below. That determines whether the Time from is before or after Time To. According to the results, show validation.
For Example: Time From 4:00 and Time To 4:30. Should be acceptable.
However if Time From 4:00 and Time To 3:30. This should not be acceptable.
Any ideas?
private void BindTime()
{
// Set the start time (00:00 means 12:00 AM)
DateTime StartTime = DateTime.ParseExact("00:00", "HH:mm", null);
// Set the end time (23:55 means 11:55 PM)
DateTime EndTime = DateTime.ParseExact("23:55", "HH:mm", null);
//Set 15 minutes interval
TimeSpan Interval = new TimeSpan(0, 15, 0);
//To set 1 hour interval
//TimeSpan Interval = new TimeSpan(1, 0, 0);
ddlTimeFrom.Items.Clear();
ddlTimeTo.Items.Clear();
while (StartTime <= EndTime)
{
ddlTimeFrom.Items.Add(StartTime.ToShortTimeString());
ddlTimeTo.Items.Add(StartTime.ToShortTimeString());
StartTime = StartTime.Add(Interval);
}
ddlTimeFrom.Items.Insert(0, new ListItem(" Select ", "0"));
ddlTimeTo.Items.Insert(0, new ListItem(" Select ", "0"));
}
When you want to validate, use this function:
private bool IsSelectionValid()
{
DateTime fromTime;
DateTime toTime;
if(!DateTime.TryParse(ddlTimeFrom.SelectedValue, out fromTime) ||
!DateTime.TryParse(ddlTimeTo.SelectedValue, out toTime))
{
return false;
}
return fromTime < toTime;
}
IsSelectionValid would give return false if fromTime is not less than toTime.
Related
I have datetime like 2019-02-10 20:39:23 and I want to round this time to the next one apart 15 min to the closest one. So it means the next one should be 2019-02-10 21:45:00 or another example 21:24:17 should became 21:45:00... The code below works fine until I have datetime like 2019-02-10 23:54:20. Then the next one rounded should be 2019-03-10 00:00:00 but I get 2019-02-10 00:00:00.
Here is how I'm doing it:
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("2019-02-10 23:54:23");
var interval = TimeSpan.FromMinutes(15);
DateTime last = NextTime(dt, interval);
Console.WriteLine(last);
}
private static DateTime NextTime(DateTime value, TimeSpan interval)
{
var temp = value.Add(new TimeSpan(interval.Ticks / 2));
var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);
return value.Date.Add(time);
}
For output I get 2019-02-10 00:00:00 instead of 2019-03-10 00:00:00
Can't figure out why doesn't turn to next day...
The return value is being calculated from the wrong variable. Use temp instead of value:
private static DateTime NextTime(DateTime value, TimeSpan interval)
{
var temp = value.Add(new TimeSpan(interval.Ticks / 2));
var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);
return temp.Date.Add(time);
}
The reason for this is because you're adding your interval to the value. If it rolls over a midnight/end of day your value.Date will return the wrong day. Since you store temp, you can return temp.Date.Add(time)
Using DateTime.Add(TimeSpan) the time is concat in the date.
I'v changed your code in this way and it did the trick:
private static DateTime NextTime(DateTime value, TimeSpan interval)
{
var temp = value.Add(new TimeSpan(interval.Ticks / 2));
var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);
if (time == new TimeSpan(0, 0, 0)) { time = new TimeSpan(24, 0,0); }
var timeDiff = time - value.TimeOfDay;
var finalDate = value.AddHours(timeDiff.Hours);
finalDate = finalDate.AddMinutes(timeDiff.Minutes);
finalDate = finalDate.AddSeconds(timeDiff.Seconds);
return finalDate;
}
I believe that must have some way more beautifull to do that but it works.
Hi any ideas on how to calculate time left to a specific hour,
i.e. we start countdown with
if currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25")
and then we parse current hour and end hour (in this example 7:25) and make a label show how many minutes and seconds are left.
I've tried making something with substracting timespan now and end time timespan but it didn't work out at all.
EDIT: The main idea is something like this, but I can't get it to work by using TimeSpan neither DateTime
string myTime;
void timer()
{
var endTime = DateTime.Parse(myTime);
var beginTime = DateTime.Now.TimeOfDay;
}
private void timer1_Tick(object sender, EventArgs e)
{
var endTime = DateTime.Parse(myTime);
var beginTime = DateTime.Now.TimeOfDay;
TimeSpan difference = endTime - beginTime;
TimeSpan currentTime = DateTime.Now.TimeOfDay;
if (currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25"))
{
label5.Text = "0";
myTime = "07:25";
timer();
label6.Text = difference;
}
}
Use DateTime instead of TimeSpan when parsing points in time. TimeSpan is for durations. The difference between two points in time (DateTime) will be a duration (TimeSpan).
var end = DateTime.Parse("21:00");
var now = DateTime.Now; // Could also be some other point in time
TimeSpan timeLeft = end-now;
Console.WriteLine(timeLeft);
Result:
00:24:25.8581440
If you don't like the seconds and fractions of seconds, you can use a custom format, e.g.
Console.WriteLine(timeLeft.ToString("hh\\:mm"));
I have to add 15 minutes to the current time and set it to a DateTime object in C#. If my current time is say 11:50 PM, and 15 minutes is added, the hour part becomes 24 and is causing the following error: "Hour, Minute, and Second parameters describe an un-representable DateTime."
public static DateTime NewTime(this DateTime dateTime)
{
int hour = dateTime.Hour;
int minute = dateTime.Minute;
if (minute > 0)
{
minute = dateTime.Minute + (15);
if (minute >= 60)
{
hour = hour + 1;
minute = 0;
}
}
return new DateTime(dateTime.Year, dateTime.Month,
dateTime.Day, hour, minute, 0);
}
Thanks
Your logic does not make sense, you are only adding minutes if the minutes are greater than 0 so what happens if they are 0?
To add time use the methods built into the type definition, no need to reinvent the wheel. Example:
public static DateTime Add15Minutes(this DateTime dateTime)
{
return dateTime.AddMinutes(15);
}
You are checking for an overflow on the minute attribute, but not the hour attribute. You could check for an overflow on the hour attribute like this:
public static DateTime NewTime(this DateTime dateTime)
{
int hour = dateTime.Hour;
int minute = dateTime.Minute;
var day = dateTime.Day;
if (minute > 0)
{
minute = dateTime.Minute + (15);
if (minute >= 60)
{
hour = hour + 1;
minute = 0;
}
}
if (hour > 24) {
day += 1;
}
return new DateTime(dateTime.Year, dateTime.Month,
day, hour, minute, 0);
}
However, you will also run into problems with the overflow of days in a month, which is even more complicated to handle. Instead, just use the built in Add function:
public static DateTime NewTime(this DateTime dateTime)
{
return new dateTime.AddMinutes(15);
}
I think you are overthinking this maybe? DateTime already provides many support methods and this will probably do what you need without the need to create an extension method:
var myValue = new DateTime(2017,3,14,23,50,0);
var result = myValue.AddMinutes(15);
This is my front end, in my case, I would like to add all the total hours of time in and time out of all my rows in my datagridview. My datagridview fields are id, employee code, date, timein and timeout.
Here is my back end, in here I computed the the late, the total hours, the day difference and the night difference. Is it possible to display on my textboxes the total hours, the late, the day diff and night based on the data on my datagridview. Sorry for my english, clarify my questions with yours.
string timeIn = datagridAttendance.CurrentRow.Cells["timeIn"].Value.ToString();
string timeOut = datagridAttendance.CurrentRow.Cells["timeOut"].Value.ToString();
DateTime tIn = Convert.ToDateTime(timeIn);
DateTime tOut = Convert.ToDateTime(timeOut);
TimeSpan span = tOut - tIn;
txtTotalHours.Text = Convert.ToString(span);
DateTime start = Convert.ToDateTime(txtStart.Text);
txtMe.Text = tIn.ToShortTimeString();
DateTime inTime = Convert.ToDateTime(txtMe.Text);
if (inTime > start)
{
TimeSpan late = inTime - start;
txtLate.Text = Convert.ToString(late);
}
else
{
txtLate.Text = "Not Late";
}
TimeSpan passLength = new TimeSpan(0, 0, 0, 1);
TimeSpan nightTime = new TimeSpan();
while (tIn < tOut)
{
tIn = tIn.Add(passLength);
if (tIn.Hour < 6 || tIn.Hour == 23)
{
nightTime = nightTime.Add(passLength);
}
}
txtNightDif.Text = Convert.ToString(nightTime);
TimeSpan day = span - nightTime;
txtDayDif.Text = Convert.ToString(day);
Your code will look like below with the arrays timein[] timeout[] being the values in each row of DataGridView
DateTime[] timein = { DateTime.Parse("1:00"), DateTime.Parse("3:00"), DateTime.Parse("5:00"), DateTime.Parse("7:00") };
DateTime[] timeout = { DateTime.Parse("2:00"), DateTime.Parse("4:00"), DateTime.Parse("6:00"), DateTime.Parse("8:00") };
TimeSpan totalTime = new TimeSpan();
for (int i = 0; i < timein.Count(); i++)
{
totalTime += timeout[i] - timein[i];
}
You can do this in your database, and then return the sum of timespans as a column. That would be better and far easier.
Interesting issue I'm facing and I just can't come up with an algorim to calculate.
Basically, what I want is to calculate a DateTime based on DateTime.Now.AddMinutes() but the Adding of minutes should take into consideration Working Hours and weekends.
In other words, if the time is currently 16:50 and i add 20 minutes, the method should return a DateTime for tomorrow morning at 08:10 (if tomorrow is not a weekend day).
I've started with some logic, but it's not complete. Does anyone have a sample which can save me a few hours of coding? This is what i've got so far:
public DateTime CalculateSLAFromNow(int minutes)
{
DateTime now = DateTime.Now;
TimeSpan slatimeaddedon = CalculateToNextWeekDay(DateTime.Now);
TimeSpan finalMinutesAddedon = slatimeaddedon.Add(new TimeSpan(0, minutes, 0));
DateTime SLATime = DateTime.Now.AddMinutes(slatimeaddedon.TotalMinutes);
return SLATime;
}
private TimeSpan CalculateToNextWeekDay(DateTime dt)
{
//Calculate.
}
public static DateTime CalculateSLAFromNow(int minutes)
{
double days = (double)minutes / 540;
DateTime now = DateTime.Now;
DateTime later = now;
while (days >= 1)
{
later = later.AddDays(1);
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
days--;
}
days = days * 540;
later = later.AddMinutes(days);
if (later.Hour > 17)
{
later = later.AddHours(15);
}
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
else if(later.DayOfWeek == DayOfWeek.Sunday)
{
later = later.AddDays(1);
}
return later;
}
There now it accounts for any number of minutes added (not the prettiest code, but it works)
Ok. Friend of mine wrote the following which works 100%. Thanks J for this. Herewith the complete solution:
private static DateTime DoCalculation(DateTime startDate, int minutes)
{
if (startDate.DayOfWeek == DayOfWeek.Sunday)
{
// if the input date is a sunday, set the actual SLA start date to the following monday morning 7:00AM
startDate = startDate.AddHours(24);
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 7, 0, 0);
}
else if (startDate.DayOfWeek == DayOfWeek.Saturday)
{
// if the input date is a saturday, set the actual SLA start date to the following monday morning 7:00AM
startDate = startDate.AddHours(48);
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 7, 0, 0);
}
DateTime resultDate = startDate;
for (int i = 0; i < minutes; i++)
{
resultDate = resultDate.AddMinutes(1);
// it is 5PM and time to go home
if (resultDate.Hour >= 17)
{
// if tomorrow is saturday
if (resultDate.AddDays(1).DayOfWeek == DayOfWeek.Saturday)
{
//add 48 hours to get us through the whole weekend
resultDate = resultDate.AddHours(48);
}
// add 14 hours to get us to next morning
resultDate = resultDate.AddHours(14);
}
}
return resultDate;
}