I have start time and end time in my asp.net web application. Now i want to validate that if start time is selected say 10:00 AM then end time should be selected with the gap of 2 hours or less. Hence if i select 01:00 PM as a end time, then this should not happen.
How can i validate the same?
If you use addition or subtraction on a DateTime class it returns a TimeSpan which can be compared in a conditional.
When creating a new TimeSpan class you can set the hours minuets and seconds in this form:
new TimeSpan(hours, minutes, seconds);
In your case you want to use:
new TimeSpan(2, 0, 0);
Try something like this:
//Assuming you created your variables and assigned them somewhere above
DateTime startTime, endTime;
if(endTime - startTime > new TimeSpan(2, 0, 0)) {
//validation error
}
Use a CompareValidator with type=DateTime to make sure EndTime > BeginTime. This will also validate they're both valid Time values.
Use a CustomValidator (C# and optionally JavaScript) to enforce the 2 hour rule.
Optionally add 1 or 2 RequiredFieldValidators
As mentioned you can use a custom validation implementation. This would check that the current time selected 'start' was no more than 2 hours previous (or exactly dependent on your conditions).
Another thing to look at is 'range-validation' which should accommodate your requirements. Take a look here on MSDN for examples: http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic5
Related
I receive a date like 1.01.2022 h:00, m:00, s:00, ms: 00
What is the best approach to get the date at the end of the day, something like: 01.01.2022 h:23, m:59, s:59, ms: 999?
I tried those 2 ways:
var endOfDay = new TimeSpan(0, 23, 59, 59, 999);
time = time.Add(endOfDay);
and
time = time.AddDays(1).AddMilliseconds(-1);
This removes all doubt down to the resolution of a single tick. In the code below, assume that dateAndTime could include a non-zero time component.
dateAndTime.Date.AddDays(1).AddTicks(-1);
This
ensures we are only working with a date that has no time component as our reference point/date
moves us to the next date at midnight
subtracts a single tick, bringing us back to our reference date with a full-resolution time component (you could do milliseconds if you prefer, just know it's less resolution).
While this works, it's generally better to consider an alternate design that doesn't rely on a time component at all (e.g. use a given date at midnight on the next day to act as a virtual end-of-day for the given reference date).
If you want just to print out the range, the action format is opinion based. If you, however, want to check if some time is within or without the day, please do it as (note >= and <)
if (timeOfQuestion >= day.Date && timeOfQuestion < day.Date.AddDays(1)) {
...
}
Using onstructions like endOfDays = time.AddDays(1).AddMilliseconds(-1) is dangerous:
please, note that day.Date.AddMilliseconds(999.5) - double value - should be within the day.
I am setting up a system to gather data from a database based on a user inputted start date and end date. The system will gather data averaged over an interval(1 hour, 6 hours, or one day for example). If the user does not input a start or end date I would like the program to set the start date to the current time minus the interval.
I currently have the user inputting the interval in the following format.
1m = 1 minute
1h = 1 hour
12h = 12 hours
3d = 3 days
So these values are not formatted like datetime. I could take the current datetime and subtract it by either minutes, hours, or days depending on the value appended (splitting on the number), but this would mean many if statements. What I would really like is a method to subtract a datetime by an arbitrary value Does anyone have a better solution?
Instead of providing predefined time intervals (that are implemented e. g. via a separate type/enum), it is much easier to let the user freely specify a TimeSpan.
This has two advantages:
The user is not restricted to predefined intervals
You can subtract the TimeSpan directly from your DateTime.Now
If restriction to limited intervals is a requirement, you can implement this in the view/window. But still this should be a TimeSpan.
I have a windows service and I would like to insert a timer. How can I check if the present time is 9:00 AM ?
I would like my service to check this every day. Thank you a lot
My try:
Datetime dt=Datetime.parse("09:00:00 everyday");
if(datetime.now -dt ==0)
{
//fire event
}
Thats kinda sily of me though.
You need to make a timer and sets its interval to the timespan between now and tomorrow 9:00 AM. Next time the timer tick, set the interval again in the same way.
You should use this Timer class:
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Please use DateTime.UtcNow.Hour to check current hour
By using UtcNow you will gets a DateTime object that is set to the current date and time on the computer, expressed as the Coordinated Universal Time (UTC).
var now = DateTime.Now;
var today = now.Date;
var nineAm = today.AddHours(9);
TimeSpan ts = nineAm - now;
var timeInMillisecondsTill9Am = ts.Milliseconds;
If(timeInMillisecondsTill9Am==0)
{
//your code goes here
}
Since you don't know when someone may shutdown or reboot your computer or service then you need to make sure that you use a method robust enough to handle these kinds of interruptions.
I suggest that when your service checks every 5 minutes or so if the time is after 9am and if the last run date is yesterday. If so, you update the last run date to day (perhaps in a simple text file) and then run the "9:00am" task. In this way your task only runs once per day, fairly close to 9am, and is robust against reboots.
You'll need to use a standard .NET timer to trigger the checks - and if you're clever enough you can make it fire a few seconds after 9am.
Let me know if that's a good solution.
I am creating a timer job in VS for sharepoint, and I want to create a Date object that only has a month and day. The reason for this is because I want this job to run annually on the specific date.
If it's not possible with a date object, then how would you go about doing this?
Here's what I've got:
DateTime value = new DateTime(2010, 1, 18);
Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.
You could always ignore the year though - or take the current year:
// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);
To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:
public struct MonthDay : IEquatable<MonthDay>
{
private readonly DateTime dateTime;
public MonthDay(int month, int day)
{
dateTime = new DateTime(2000, month, day);
}
public MonthDay AddDays(int days)
{
DateTime added = dateTime.AddDays(days);
return new MonthDay(added.Month, added.Day);
}
// TODO: Implement interfaces, equality etc
}
Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...
Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".
How about creating a timer with the next date?
In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create.
DateTime is always represents a specific date and time but not a recurring date.
There is no such thing like a DateTime without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
Anyway you need 'Year'.
In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.
You can create a custom combobox using this: Customizable ComboBox Drop-Down.
1- In VS create a user control.
2- See the code in the link above for impelemnting that control.
3- Create another user control and place in it 31 button or label and above them place a label to show months.
4- Place the control in step 3 in your custom combobox.
5- Place the control in setp 4 in step 1.
You now have a control with only days and months. You can use any year that you have in your database or ....
I'm working on a small web form that requires the user to input (among other things), the scheduled backup time of whatever server they're adding to the system. The problem is, I'm struggling to find out the best way to take the user input and build a DateTime object (which is what the database requires).
I only really care about the Day of Week, Time of Day (12 or 24 hour clock).
I thought about just creating an empty DateTime object and then just adding my input values from the user, but you can only get, not set, the day of week, time of day, etc.
I've been looking at the Calender asp control, which would work for the day of the week selection, but I can't seem to find any support of time of day.
Thanks.
I don't think you want to use a DateTime for a recurring event such as a backup. A DateTime is useful for storing a particular date and time, but not a "template" for a recurring event. Instead I'd use separate columns to store the day of week value (0-6) and time of date (minutes after midnight) for the event.
If you going to use datepicker here is one great sample for adding JQuery date picker using C#. That helped me including in my project evrn if I did know anything abaut JQuery and java sripts at all.
DateTime is a immutable value type. You cannot set anything on it.
Assumed that you stick with DateTime on the DB and you don't want to use a DateTimePicker control.
You have to specify how the day of week and the time should be represented in the DateTime. You can start with DateTime.MinValue, the 1.1.0001, 12:00 at midnight, and add the day of week and the time. unfortunately, a regular DateTime field in a SqlServer 2005 is not able to store this date. So lets move it to the year 2000. The 1.1.2000 was a Saturday. You could calculate the DateTime like this:
int dayOfWeek; // 0 = mon, 6 = son
DateTime time;
DateTime scheduleTime = new DateTime(2000, 1, (dayOfWeek + 2) % 6 + 1)
+ time.TimeOfDay;
But honestly, I wouldn't do it. It smells. I just answered your question. Listen to tvanfosson. He said everything that needs to be said.