Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1283
  • Last Modified:

How do I write a statement in C# that only runs if a date falls between two dates?

I have written the attached C# .Net code within Visual Studio 2008. Due to the UK recently entering the DST timezone I only want my code to be run when the _announcementShowDate variable falls between the last week in October and the last week in March. Can someone help?
private void delayUntilShowDate_InitializeTimeoutDuration(object sender, EventArgs e)
        {
            //variable containing show date and time value declared by the user in the SP list
            DateTime _announcementShowDate = Convert.ToDateTime(workflowProperties.Item.GetFormattedValue("Show Date"));
 
            //variable containing tomorrows date at 7:30am
            DateTime _TomorrowSevenThirtyAM = System.DateTime.Today.AddDays(1).AddHours(07).AddMinutes(30);
 
            //variable containing todays date in the format: **-**-** 00:00:00
            DateTime _today = System.DateTime.Today;
 
            //activating the delay
            if (_announcementShowDate < _TomorrowSevenThirtyAM && workflowProperties.Item["OTD"].ToString() == "No")
            {
                //find show date
                DateTime NextStop = _announcementShowDate;
 
                //setting time of show date. if below is set to 00:00 then the time is taken from sharepoint list show date column
                NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                //send email at time of show date
                //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                //OR... (both achieve the same)
                this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                //append email information to the email status field
                workflowProperties.Item["Email Status"] = "Sending on: " + NextStop.ToLongDateString() + " at " + NextStop.ToShortTimeString();
                workflowProperties.Item.Update();
            }
            //activating the delay for "on the day" items 
            else if (_announcementShowDate.Date == _today.Date && workflowProperties.Item["OTD"].ToString() == "Yes")
            {
                //find show date
                DateTime NextStop = _announcementShowDate;
 
                //setting time of show date. If set to 00:00 then time is taken from sharepoint NewToday.aspx
                NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                //send email at time of show date
                //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                workflowProperties.Item["Email Status"] = "Sending today at " + NextStop.ToShortTimeString();
                workflowProperties.Item.Update();
            }
            //activating the delay for future items
            else if (_announcementShowDate.Date > _today.Date && workflowProperties.Item["OTD"].ToString() == "No")
            {
                //find show date
                DateTime NextStop = _announcementShowDate;
 
                //setting time of show date. if set to 00:00 then time is taken from sharepoint list
                NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                //send email at time of show date
                //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                workflowProperties.Item["Email Status"] = "Sending on: " + NextStop.ToLongDateString() + " at " + NextStop.ToShortTimeString();
                workflowProperties.Item.Update();
            }
            //if the above conditions are not met append "not sent" information to the email status field
            else
            {
                //find show date
                DateTime NextStop = _announcementShowDate;
 
                //setting time of show date. if set to 00:00 then time is taken from sharepoint list
                NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                //send email at time of show date
                this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
                
                workflowProperties.Item["Email Status"] = "Not Sent, please check your entry and re-submit";
                workflowProperties.Item.Update();
 
                //throws an exception which is then handled within the designer before flagging the terminate activity
                throw new System.Exception();
 
            }
        }

Open in new window

0
Shepwedd
Asked:
Shepwedd
  • 9
  • 8
1 Solution
 
spprivateCommented:
I guess you can use the Daylight time class in .Net rather than calculation of your own.
Let me have a look into it
0
 
spprivateCommented:
Here is the class which if you pass the year will give you the daylight start date and end date for the respective time zones.
So you can check your variable not to fall between these two dates and that should solve it.


using System.Globalization;
static void CreateDaylightTime(int year)
        {
            // Create a DaylightTime object for the specified year.
            DaylightTime daylight =
                localZone.GetDaylightChanges(year);
 
            // Display the start and end dates and the time change.
            Console.WriteLine("{0,-7}{1,-20:yyyy-MM-dd HH:mm}" +
                "{2,-20:yyyy-MM-dd HH:mm}{3}",
                year, daylight.Start, daylight.End, daylight.Delta);
        }
 
In your method call CreateDaylightTime(2009)
and get the variables to check between daylight.Start and daylight.End

Open in new window

0
 
ShepweddAuthor Commented:
Excellent, but I'm not too sure how to get my variable (_announcementShowDate) to check whether it falls between daylight.Start and daylight.End?

Any help is appreciated.
0
Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
ShepweddAuthor Commented:
I also get an error:

The name localZone does not exist in the current context?

I also noticed that there is a built in "IsDaylightSavingTime" class, can this not be used?
0
 
spprivateCommented:
Oops
My bad. forgot to add the variable Look at the code.

using System.Globalization;
static TimeZone localZone = TimeZone.CurrentTimeZone;
 
static void CreateDaylightTime(int year)
        {
            // Create a DaylightTime object for the specified year.
            DaylightTime daylight =
                localZone.GetDaylightChanges(year);
 
            // Display the start and end dates and the time change.
            Console.WriteLine("{0,-7}{1,-20:yyyy-MM-dd HH:mm}" +
                "{2,-20:yyyy-MM-dd HH:mm}{3}",
                year, daylight.Start, daylight.End, daylight.Delta);
        }
 

Open in new window

0
 
spprivateCommented:
Yes,You can use that as well.

if (localZone.IsDaylightSavingTime(DateTime.Now)) { Console.WriteLine("Yes I am daylight" + DateTime.Now); }
            if (!localZone.IsDaylightSavingTime(DateTime.Now.AddMonths(9))) { Console.WriteLine("No I am not" + DateTime.Now.AddMonths(9)); }

For you case it will be like
if(!localZone.IsDaylightSavingTime(_announcementShowDate)
{Your Code}
The IsDaylightSavingTime class will return true if it is a DST date.
So in your case you check for negative condition with !.
 
HTH

Open in new window

0
 
ShepweddAuthor Commented:
Thanks but now I get these errors:

Cannot implicitly convert type 'System.Globalization.DaylightTime' to '<my namespace>.<my class name>'.

'<my namespace>.<my class name>' does not contain a definition for 'Start' and no extension method 'Start' accepting a first argument of type '<my namespace>.<my class name>' could be found.

'<my namespace>.<my class name>' does not contain a definition for 'End' and no extension method 'End' accepting a first argument of type '<my namespace>.<my class name>' could be found.

'<my namespace>.<my class name>' does not contain a definition for 'Delta' and no extension method 'Delta' accepting a first argument of type '<my namespace>.<my class name>' could be found.

0
 
spprivateCommented:
You dont have to get into all these.Just IsDaylightSaving class helps.
I have put two line in your code and wrapped a if condition on other parts.
Check this out.
 private void delayUntilShowDate_InitializeTimeoutDuration(object sender, EventArgs e)
        {
  public TimeZone localZone = TimeZone.CurrentTimeZone;
            //variable containing show date and time value declared by the user in the SP list
            DateTime _announcementShowDate = Convert.ToDateTime(workflowProperties.Item.GetFormattedValue("Show Date"));
 
            //variable containing tomorrows date at 7:30am
            DateTime _TomorrowSevenThirtyAM = System.DateTime.Today.AddDays(1).AddHours(07).AddMinutes(30);
 
            //variable containing todays date in the format: **-**-** 00:00:00
            DateTime _today = System.DateTime.Today;
            //My Code for your condition
            if(!localZone.IsDaylightSavingTime(_announcementShowDate))
            {
                //activating the delay
                if (_announcementShowDate < _TomorrowSevenThirtyAM && workflowProperties.Item["OTD"].ToString() == "No")
                {
                    //find show date
                    DateTime NextStop = _announcementShowDate;
 
                    //setting time of show date. if below is set to 00:00 then the time is taken from sharepoint list show date column
                    NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                    //send email at time of show date
                    //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                    //OR... (both achieve the same)
                    this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                    //append email information to the email status field
                    workflowProperties.Item["Email Status"] = "Sending on: " + NextStop.ToLongDateString() + " at " + NextStop.ToShortTimeString();
                    workflowProperties.Item.Update();
                }
                //activating the delay for "on the day" items 
                else if (_announcementShowDate.Date == _today.Date && workflowProperties.Item["OTD"].ToString() == "Yes")
                {
                    //find show date
                    DateTime NextStop = _announcementShowDate;
 
                    //setting time of show date. If set to 00:00 then time is taken from sharepoint NewToday.aspx
                    NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                    //send email at time of show date
                    //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                    this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                    workflowProperties.Item["Email Status"] = "Sending today at " + NextStop.ToShortTimeString();
                    workflowProperties.Item.Update();
                }
                //activating the delay for future items
                else if (_announcementShowDate.Date > _today.Date && workflowProperties.Item["OTD"].ToString() == "No")
                {
                    //find show date
                    DateTime NextStop = _announcementShowDate;
 
                    //setting time of show date. if set to 00:00 then time is taken from sharepoint list
                    NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                    //send email at time of show date
                    //((DelayActivity)sender).TimeoutDuration = NextStop.Subtract(DateTime.Now);
                    this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                    workflowProperties.Item["Email Status"] = "Sending on: " + NextStop.ToLongDateString() + " at " + NextStop.ToShortTimeString();
                    workflowProperties.Item.Update();
                }
                //if the above conditions are not met append "not sent" information to the email status field
                else
                {
                    //find show date
                    DateTime NextStop = _announcementShowDate;
 
                    //setting time of show date. if set to 00:00 then time is taken from sharepoint list
                    NextStop = NextStop.AddHours(00).AddMinutes(00);
 
                    //send email at time of show date
                    this.delayUntilShowDate.TimeoutDuration = NextStop.Subtract(DateTime.Now);
 
                    workflowProperties.Item["Email Status"] = "Not Sent, please check your entry and re-submit";
                    workflowProperties.Item.Update();
 
                    //throws an exception which is then handled within the designer before flagging the terminate activity
                    throw new System.Exception();
 
                }
            }
        }

Open in new window

0
 
spprivateCommented:
Take the access modifier of the localzone variable

It should be
 TimeZone localZone = TimeZone.CurrentTimeZone;

HTH
0
 
ShepweddAuthor Commented:
Thanks for your code but upon debugging my application my _announcementShowDate variable is still an hour ahead of what it should be? Debug also showed that my application does not enter your if statement?
0
 
ShepweddAuthor Commented:
It's as if my code thinks I'm in the wrong timezone but within debug it stated that my CurrentTimeZone was GMT which is correct? I'm not too sure why the time is declared an hour ahead of GMT?
0
 
spprivateCommented:
The if condition will not execute now because today untill oct is day light saving.
Your code will work only when it is not daylight saving which is from oct-march.
Remember .,the if condition is  IF not Daylight do stuff.

Also check your system time,there was a patch from microsoft so that changed DST is in effect.Anyway that should not matter,but IF CONDITION will not work untill Oct.
The way to test is ,do a _announcementShowDate.addMonth(8) and then test.
At that time it would be December which is out DST and it will get into the condition
0
 
ShepweddAuthor Commented:
Yes, you're right, the IF condition executes when I add 8 months, great! However, this does not correct my initial problem as for some reason my _announcementShowDate variable shows, for example, 19:40 when my system time shows 18:40? I need these to match. Everything was functioning correctly before the weekend when the UK went into DST, now I can't get my times to match? I would install the Microsoft patch but I would rather write code so I have more control.

Thanks.
0
 
ShepweddAuthor Commented:
I suppose all I need to do now if get my variable to subtract an hour, do you know how to do this? There seems to be an AddHour but not a SubtractHour?
0
 
spprivateCommented:
AddHours(-1) will do the trick.
My only assumption would be that if you are running on a  web server which is on different time zone (gmt+1).Just a wild guess cos I have personally ran into such issue when our server was in texas central time where as users where in atlanta Eastern time.

Can you print the time zone and current time to see what is it coming up
0
 
spprivateCommented:
One more thing I found is that there is a patch needs to be applied in your machine for the DST to be functioning correctly.Follow this article and update the patch given in the last part of the article.Most possibly this could be the reason.

http://www.netadmintools.com/art575.html
0
 
ShepweddAuthor Commented:
Thanks
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

  • 9
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now