Solved

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

Posted on 2009-04-01
17
1,270 Views
Last Modified: 2013-12-17
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
Comment
Question by:Shepwedd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
17 Comments
 
LVL 15

Expert Comment

by:spprivate
ID: 24040173
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24040264
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
 

Author Comment

by:Shepwedd
ID: 24040336
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Shepwedd
ID: 24040417
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24040896
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24040937
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
 

Author Comment

by:Shepwedd
ID: 24041005
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24041164
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24041181
Take the access modifier of the localzone variable

It should be
 TimeZone localZone = TimeZone.CurrentTimeZone;

HTH
0
 

Author Comment

by:Shepwedd
ID: 24041419
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
 

Author Comment

by:Shepwedd
ID: 24041463
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24041571
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
 

Author Comment

by:Shepwedd
ID: 24041707
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
 

Author Comment

by:Shepwedd
ID: 24041753
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
 
LVL 15

Expert Comment

by:spprivate
ID: 24041855
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
 
LVL 15

Accepted Solution

by:
spprivate earned 500 total points
ID: 24041911
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
 

Author Closing Comment

by:Shepwedd
ID: 31565341
Thanks
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question