Question

How to calculate the number of hours in a day

Asked by: pmengal

I would like to know how to calculate the number of hours in a day, using VBA in Excel.

In .NET, it's pretty easy:

public static int GetNumHourInDay(DateTime targetday )
        {
            int num;
            targetday = targetday.Date;
            TimeSpan offset1 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday);
            TimeSpan offset2 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday.AddDays(2)); //because the utc change a Day+1 hour + 3
            if (offset1 > offset2)
            {
                num = 25;
            }
            else if (offset1 < offset2)
            {
                num = 23;
            }
            else
            {
                num = 24;
            }
            return num;
        }

For some reason, I need the same function in VBA. Thank you.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-01-11 at 06:23:44ID23075660
Tags

Microsoft

,

Excel

Topics

Microsoft Excel Spreadsheet Software

,

Math & Science

,

VB Script

Participating Experts
5
Points
250
Comments
28

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. UTC int Convert to standard DateTime how?
    I have a UTC int, how do I convert this to a standard datetime. Example, the UTC int 1104178047 is the date of 2005-03-02. I need to do the conversion in tsql. Both date and time are needed. There are several proposed solutions I've found on the web, but they are incorrec...
  2. Take a  GMT+1 (Central European Time)  DateTime and …
    I'm reading times from a txt file that is formatted by the GMT+1 timezone. I'd like to convert this datetime object to UTC before I insert it into a database, how would I go about doing that?
  3. .net calculate timespan in hours and minutes c# vb.net
    The code snippet below calculates the timespan between two periods DateTime dtStart = DateTime.Parse(StartTime.Text); DateTime dtEnd = DateTime.Parse(EndTime.Text); TimeSpan ts = dtEnd.Subtract(dtStart); /* calculate time wi...
  4. Convert SQL datetime from UTC to local
    I have a MS SQL database in which all datetimes are stored as UTC(GMT). All work that this database keeps track of is in the EST time zone. I need to make a stored procedure that can convert a given datetime to whatever the local time should be. I've figured out how to do ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: gtglonerPosted on 2008-01-11 at 06:29:13ID: 20636536

I think we need some more information here, what are your parameters for the calculation of hours?

 

by: MrBullwinklePosted on 2008-01-11 at 06:29:29ID: 20636538

There tends to be 24hours in a day. You can assume that and save processing.

I couldn't figure out what the code did, but I fixed the syntax for VB.  I'm not sure if these functions exist in VB, so they're probably going to crash.
TimeSpan offset1 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday)

public function GetNumHourInDay(DateTime targetday ) as integer
            dim num as integer
            targetday = targetday.Date
            TimeSpan offset1 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday)
            TimeSpan offset2 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday.AddDays(2)) 'because the utc change a Day+1 hour + 3
            if (offset1 > offset2) then
                num = 25
            elseif (offset1 < offset2) then
                num = 23
            else
                num = 24
            end if
            GetNumHourInDay= num
end function
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: pmengalPosted on 2008-01-11 at 06:31:30ID: 20636560

The TimeZone object is linked to .NET, so it won't work.

Thanks anyway

 

by: pmengalPosted on 2008-01-11 at 06:32:11ID: 20636567

The only parameter is a date. I want to know the number of hour for the 8/4/2008 or the 14/14/2009.

Thank you

 

by: MrBullwinklePosted on 2008-01-11 at 06:35:27ID: 20636592

I'm not following what you're trying to do. Is that when 'Daylight Savings' occurs?
VB has a function called DateDiff() if you want to look into that.

Or, just return 24 everytime, you'll be right 363/365 % of the time, thats within 10% margin of error ;-)

 

by: pmengalPosted on 2008-01-11 at 06:45:03ID: 20636662

I want a VBA function that return the number of hours contained in the specified date.

So yes, the daylight saving is important. If not, my function would have just returned 24 ;)

 

by: gtglonerPosted on 2008-01-11 at 06:46:36ID: 20636680

I want to know the number of hour for the 8/4/2008 or the  >>14/14/2009.<< ??

Now I am really confused, which month is the 14th?

 

by: pmengalPosted on 2008-01-11 at 06:47:40ID: 20636692

gtgloner,

it's just an example, I want to know the number of hours in ANY date.

Thanks

 

by: jellPosted on 2008-01-11 at 06:49:19ID: 20636709

It may be a local thing, and admittedly I have had a few, but I'm pretty sure there are 24 hours in a day where I come from.

Therefore:

Public Const NO_OF_HOURS_IN_DAY as Integer = 24

...should do it for you.

There are, as mentioned above, 2 days of the year for most countries when there are 23 and 25 hours respectively, but the net difference is zero, meaning every day of the year has an average of exactly 24 hours.


"Or, just return 24 everytime, you'll be right 363/365 % of the time, thats within 10% margin of error"

...actually is 0.54%, so quite acceptable really.


"The only parameter is a date. I want to know the number of hour for the 8/4/2008 or the 14/14/20092

...this would be 24 (see above), and probably 24 (should we decide to do away with the annoying habit of incrementing years at the end of the 12th month).


Hope this helps.

Jell


 

by: gtglonerPosted on 2008-01-11 at 06:49:25ID: 20636710

OK, I think I have got it now, you want something that will detect when we go on and off daylight saving time and show the hours in those days as being 23 or 25?

 

by: MrBullwinklePosted on 2008-01-11 at 06:52:40ID: 20636749

You just need to store the dates for DST (or find a function that gets them from someplace).  I know they moved American DST just so it could screw up my Outlook appointments.

 

by: pmengalPosted on 2008-01-11 at 06:53:16ID: 20636756

Ok guys... I will put 24 and when we will have daylight saving and my company will loose millions I will send you the bill ;)

Seriously, I have the code in C#.NET in my question. I need the equivalent in VBA. That's it ;)

 

by: jellPosted on 2008-01-11 at 06:58:04ID: 20636799

Well actually, you'll lose millions on the day with 23 hours, but make it all back again on the day with 25. Less a nominal amount of interest I suppose...

;)

J

 

by: pmengalPosted on 2008-01-11 at 07:00:39ID: 20636831

jell,

haha, it don't work like that ;) The main problem is interaction between companies. It's in energy sector, so it's why this imply such big amount of money.

The system stop working that is. This happened in a previous project... sadly.

 

by: BadotzPosted on 2008-01-11 at 07:05:04ID: 20636874

<$.02>
In Arizona, they fo not allow DST. There may be other states that do not. What about the world in general?

DST is made up. As ear as the Earth is concerned, there are 24 hours in a day. The Earth doesn't speed up or slow down.

And since the time shift occurrs at 2:00 AM, on a Sunday, it is doubtful that your company will lose millions of whatever it is you are afraid they will lose.
</$.02>

 

by: jellPosted on 2008-01-11 at 07:07:56ID: 20636907

;) I jest.

Seriously though, there isn't the same classes available in VBA as there is in .Net

Another expert may know differently, but I think you'd have to write a function to calculate it manually which might be tricky due it only being applicable in Europe & North America - depends on the scope of your application I suppose.

What you could do, and I'd only recommend this if absolutely necessary, is to batch your C# code into a registered COM interface and use it in Excel.

The following, which I found in Wiki, would make a manual calc extremely though.

In a typical case where a one-hour shift occurs at 02:00 local time, in spring the clock jumps forward from 02:00 standard time to 03:00 DST and the day has 23 hours, whereas in autumn the clock jumps backward from 02:00 DST to 01:00 standard time, repeating that hour, and the day has 25 hours. A digital display of local time does not read 02:00 exactly, but instead jumps from 01:59:59.9 either forward to 03:00:00.0 or backward to 01:00:00.0. In this example, a location observing UTC+10 during standard time is at UTC+11 during DST; conversely, a location at UTC−10 during standard time is at UTC−9 during DST.

Clock shifts are usually scheduled near a weekend midnight to lessen disruption to weekday schedules. A one-hour shift is customary, but Australia's Lord Howe Island uses a half-hour shift.[78] Twenty-minute and two-hour shifts have been used in the past.

Coordination strategies differ when adjacent time zones shift clocks. The European Union shifts all at once, at 01:00 UTC; for example, Eastern European Time is always one hour ahead of Central European Time.[70] Most of North America shifts at 02:00 local time, so its zones do not shift at the same time; for example, Mountain Time can be temporarily either zero or two hours ahead of Pacific Time. Australian districts go even further and do not always agree on start and end dates; for example, to start DST in 2006 Tasmania shifted clocks forward on 1 October, Western Australia on 3 December, and the remaining DST-observing areas on 29 October.[79]

Start and end dates vary with location and year. Since 1996 European Summer Time has been observed from the last Sunday in March to the last Sunday in October; previously the rules were not uniform across the European Union.[70] Starting in 2007, most of the United States and Canada observe DST from the second Sunday in March to the first Sunday in November, almost two-thirds of the year.[80] The 2007 U.S. change was part of the Energy Policy Act of 2005; previously, from 1987 through 2006, the start and end dates were the first Sunday in April and the last Sunday in October, and Congress retains the right to go back to the previous dates once an energy-consumption study is done.[81]

Beginning and ending dates are the reverse in the southern hemisphere. For example, mainland Chile observes DST from the second Saturday in October to the second Saturday in March, with transitions at 24:00 local time.[82] The time difference between the United Kingdom and mainland Chile may therefore be three, four, or five hours, depending on the time of year.

 
Time zones often lie west of their idealized boundaries, resulting in year-round DST.Western China, Iceland, and other areas skew time zones westward, in effect observing DST year round without complications from clock shifts. For example, Saskatoon, Saskatchewan is at 106°39′W longitude, slightly west of center of the idealized Mountain Time Zone (105°W), but the time in Saskatchewan is Central Standard Time (90°W) year-round so Saskatoon is always about 67 minutes ahead of mean solar time.[83] Conversely, northeast India and a few other areas skew time zones eastward, in effect observing negative DST.[24] The United Kingdom and Ireland experimented with year-round DST from 1968 to 1971 but abandoned it because of its unpopularity, particularly in northern regions.[84]

Western France, Spain, and other areas skew time zones and shift clocks, in effect observing DST in winter with an extra hour in summer. For example, Nome, Alaska is at 165°24′W longitude, which is just west of center of the idealized Samoa Time Zone (165°W), but Nome observes Alaska Time (135°W) with DST, so it is slightly more than two hours ahead of the sun in winter and three in summer.[85]

DST is generally not observed near the equator, where sunrise times do not vary enough to justify it. Some countries observe it only in some regions; for example, southern Brazil observes it while equatorial Brazil does not.[86] Only a minority of the world's population uses DST because Asia and Africa generally do not observe it.


Jell

 

by: BadotzPosted on 2008-01-11 at 07:14:12ID: 20636951

<$.02>This horse is dead.</$.02>

 

by: pmengalPosted on 2008-01-11 at 07:14:32ID: 20636955

Badotz,

If the function has to work with DST, this is because it will be used in a country that follow DST.

I know DST is made up, and It's not the problem. The problem is that it exist.

You don't know anything about the company I'm working for... except that it's in energy sector. I can explain you why in details if you are interest, but in a private email.

If you can't just answer my question, please don't post at all. I use Expert Exchange to because it can save me a lot of time searching ;)

 

by: jellPosted on 2008-01-11 at 07:20:00ID: 20637011

<$.02>This horse is dead.</$.02>


...so this parrot.   HELLOOOOOOOOOOOOOOOOOO Polly  !


;)

 

by: BadotzPosted on 2008-01-11 at 07:22:39ID: 20637034

A Google search for

daylight savings time

turns up 3,610,000 English pages

The very first link provides a list of dates for the beginning and ending of DST from 3004 through 2010. It even has a calculator for years after 2011.

You do not need to calculate the dates, merely check them against a list.

 

by: BadotzPosted on 2008-01-11 at 07:23:33ID: 20637047

Sorry, dates from 2004 through 3004.

 

by: BadotzPosted on 2008-01-11 at 07:24:18ID: 20637057

aarrgghh - Dates from 2004 rthrough 2010. Where's my coffee?

 

by: BadotzPosted on 2008-01-11 at 07:27:35ID: 20637100

And here is the javascript that does the dirty work (excerpted from http://webexhibits.org/daylightsaving/index.html )

// this version (JavaScript1.1+) does NOT display NaN.
function WhatDates() {
  var thisYear, AprilDate, OctoberDate, MarchDateEU, OctoberDateEU, MarchDate, NovemberDate;
  thisYear = Math.round(parseInt(document.forms[0].y.value));
 
 AprilDate = (2+6 * thisYear - Math.floor (thisYear / 4) ) % 7 + 1;
 OctoberDate=  (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
 
 MarchDate = 14 - (Math.floor (1 + thisYear * 5 / 4) % 7);
 NovemberDate = 7 - (Math.floor (1 + thisYear * 5 / 4) % 7);
  
 MarchDateEU =  (31-( Math.floor (thisYear * 5 / 4) + 4) % 7);
 OctoberDateEU =  (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
 
 
document.getElementById("startu").innerHTML= thisYear>2006?("March "+MarchDate):("April "+AprilDate);
document.getElementById("stopu").innerHTML = thisYear>2006?("November "+NovemberDate):("October "+OctoberDate);
 
document.getElementById("starte").innerHTML= "March "+MarchDateEU;
document.getElementById("stope").innerHTML = "October "+OctoberDateEU;
 
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: BadotzPosted on 2008-01-11 at 07:28:27ID: 20637113

Line 4 gets the year from the <input>
Lines 16 through 20 output the results

 

by: ChizlPosted on 2008-01-13 at 22:33:57ID: 20651269

I think, if I'm not loosing my mind after reading all of this, your just wanting to know if DST is changing in the next day or not..   Correct?

Well your code will always return 24.  Both of the follow will always return in my case -06:00 even with a time change coming in in 2 hours..   I just did a test to validate it.   Feb 17th is the next time change..   Check for yourself.   I think your best bet is setting up an XML file or something that gives you all the date's of when time changes.   Since there are only 2 a year for most, you shouldnt have to store that much.   http://www.timeanddate.com/time/dstevents.html

TimeSpan offset1 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday);
TimeSpan offset2 = TimeZone.CurrentTimeZone.GetUtcOffset(targetday.AddDays(2)); 

                                              
1:
2:

Select allOpen in new window

 

by: pmengalPosted on 2008-01-13 at 23:49:46ID: 20651511

Chizi, interesting.

I'll check this now and tell you. If you are right, I split points between Badotz and you.

 

by: pmengalPosted on 2008-01-14 at 00:20:51ID: 20651644

Hi,

You were almost right Chizi... But the function work perfectly. The reason is that this is not a "normal" day (from 0am to 0am), but a "gaz day" that starts at 6am (and then ends at 6am) ;)

 

by: BadotzPosted on 2008-01-14 at 08:03:43ID: 20653914

No worries - glad to help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...