Working with Dates and Times - Working with Formulas and Functions - Microsoft Excel 2016 BIBLE (2016)

Microsoft Excel 2016 BIBLE (2016)

Part II
Working with Formulas and Functions

Chapter 12
Working with Dates and Times

IN THIS CHAPTER

1. Getting an overview of dates and times in Excel

2. Using Excel date-related functions

3. Working with Excel time-related functions

Many worksheets contain dates and times in cells. For example, you might track information by date or create a schedule based on time. Beginners often find that working with dates and times in Excel can be frustrating. To work with dates and times, you need a good understanding of how Excel handles time-based information. This chapter provides the information you need to create powerful formulas that manipulate dates and times.

Note

The dates in this chapter correspond to the U.S. English language date format: month/day/year. For example, the date 3/1/1952 refers to March 1, 1952, not January 3, 1952. I realize that this setup is illogical, but that's the way Americans have been trained. I trust that the non-American readers of this book can make the adjustment.

How Excel Handles Dates and Times

This section presents a quick overview of how Excel deals with dates and times. It covers Excel's date and time serial number system. It also provides some tips for entering and formatting dates and times.

Understanding date serial numbers

To Excel, a date is simply a number. More precisely, a date is a serial number that represents the number of days since the fictitious date of January 0, 1900. A serial number of 1 corresponds to January 1, 1900; a serial number of 2 corresponds to January 2, 1900; and so on. This system makes it possible to create formulas that perform calculations with dates. For example, you can create a formula to calculate the number of days between two dates (just subtract one from the other).

Excel support dates from January 1, 1900, through December 31, 9999 (serial number = 2,958,465).

You may wonder about January 0, 1900. This nondate (which corresponds to date serial number 0) is actually used to represent times that aren't associated with a particular day. This concept becomes clear later in this chapter. (See “Entering times.”)

To view a date serial number as a date, you must format the cell as a date. Choose Home image Number image Number Format. This drop-down control provides you with two date formats. To select from additional date formats, see “Formatting dates and times,” later in this chapter.

Choose Your Date System: 1900 or 1904

Excel supports two date systems: the 1900 date system and the 1904 date system. Which system you use in a workbook determines what date serves as the basis for dates. The 1900 date system uses January 1, 1900, as the day assigned to date serial number 1. The 1904 date system uses January 1, 1904, as the base date. By default, Excel for Windows uses the 1900 date system, and pre-2011 versions of Excel for Mac use the 1904 date system.

Excel for Windows supports the 1904 date system for compatibility with older Mac files. You can choose the date system for the active workbook in the Advanced section of the Excel Options dialog box. (It's in the When Calculating This Workbook subsection.) Generally, you should use the default 1900 date system. And you should exercise caution if you use two different date systems in workbooks that are linked. For example, assume that Book1 uses the 1904 date system and contains the date 1/15/1999 in cell A1. Assume that Book2 uses the 1900 date system and contains a link to cell A1 in Book1. Book2 displays the date as 1/14/1995. Both workbooks use the same date serial number (34713), but they're interpreted differently.

One advantage to using the 1904 date system is that it enables you to display negative time values. With the 1900 date system, a calculation that results in a negative time (for example, 4:00 pm–5:30 pm) cannot be displayed. When using the 1904 date system, the negative time displays as –1:30 (that is, a difference of 1 hour and 30 minutes).

Entering dates

You can enter a date directly as a serial number (if you know the serial number) and then format it as a date. More often, you enter a date by using any of several recognized date formats. Excel automatically converts your entry into the corresponding date serial number (which it uses for calculations), and it applies the default date format to the cell so that it displays as an actual date rather than as a cryptic serial number.

For example, if you need to enter June 18, 2016, into a cell, you can enter the date by typing June 18, 2016 (or any of several different date formats). Excel interprets your entry and stores the value 42539, the date serial number for that date. It also applies the default date format, so the cell contents may not appear exactly as you typed them.

Note

Depending on your regional settings, entering a date in a format such as June 18, 2016, may be interpreted as a text string. In such a case, you need to enter the date in a format that corresponds to your regional settings, such as 18 June 2016.

When you activate a cell that contains a date, the Formula bar shows the cell contents formatted by using the default date format — which corresponds to your system's short date format. The Formula bar doesn't display the date's serial number. If you need to find out the serial number for a particular date, format the cell with a nondate number format.

Tip

To change the default date format, you need to change a systemwide setting. From the Windows Control Panel, select Regional and Language Options. The exact procedure varies, depending on the version of Windows you use. Look for the drop-down list that enables you to change the Short Date Format. The setting you choose determines the default date format that Excel uses to display dates in the Formula bar.

Table 12.1 shows a sampling of the date formats that Excel recognizes (using the U.S. settings). Results will vary if you use a different regional setting.

Table 12.1 Date Entry Formats Recognized by Excel

Entry

Excel Interpretation (U.S. Settings)

6-18-16

June 18, 2016

6-18-2016

June 18, 2016

6/18/116

June 18, 2016

6/18/2016

June 18, 2016

6-18/16

June 18, 2016

June 18, 2016

June 18, 2016

Jun 18

June 18 of the current year

June 18

June 18 of the current year

6/18

June 18 of the current year

6-18

June 18 of the current year

18-Jun-2016

June 18, 2016

2016/6/18

June 18, 2016

As you can see in Table 12.1, Excel is rather flexible when it comes to recognizing dates entered into a cell. It's not perfect, however. For example, Excel does not recognize any of the following entries as dates:

· June 18 2016

· Jun-18 2016

· Jun-18/2016

Rather, it interprets these entries as text. If you plan to use dates in formulas, make sure that Excel can recognize the date you enter as a date; otherwise, the formulas that refer to these dates will produce incorrect results.

If you attempt to enter a date that lies outside the supported date range, Excel interprets it as text. If you attempt to format a serial number that lies outside the supported range as a date, the value displays as a series of hash marks (#########).

Searching for Dates

If your worksheet uses many dates, you may need to search for a particular date by using the Find and Replace dialog box (Home image Editing image Find & Select image Find, or Ctrl+F). Excel is rather picky when it comes to finding dates. You must enter the date as it appears in the Formula bar. For example, if a cell contains a date formatted to display as June 19, 2016, the date appears in the Formula bar using your system's short date format (for example, 6/19/2016). Therefore, if you search for the date as it appears in the cell, Excel won't find it. But it will find the cell if you search for the date in the format that appears in the Formula bar.

Understanding time serial numbers

When you need to work with time values, you extend the Excel date serial number system to include decimals. In other words, Excel works with times by using fractional days. For example, the date serial number for June 1, 2016, is 42522. Noon (halfway through the day) is represented internally as 42522.5.

The serial number equivalent of one minute is approximately 0.00069444. The following formula calculates this number by multiplying 24 hours by 60 minutes and dividing the result into 1. The denominator consists of the number of minutes in a day (1,440).

=1/(24*60)

Similarly, the serial number equivalent of one second is approximately 0.00001157, obtained by the following formula:

=1/(24*60*60)

In this case, the denominator represents the number of seconds in a day (86,400).

In Excel, the smallest unit of time is one 1,000th of a second. The time serial number shown here represents 23:59:59.999 (one 1,000th of a second before midnight):

0.99999999

Table 12.2 shows various times of day along with each associated time serial number.

Table 12.2 Times of Day and Their Corresponding Serial Numbers

Time of Day

Time Serial Number

12:00:00 am (midnight)

0.00000000

1:30:00 am

0.06250000

7:30:00 am

0.31250000

10:30:00 am

0.43750000

12:00:00 pm (noon)

0.50000000

1:30:00 pm

0.56250000

4:30:00 pm

0.68750000

6:00:00 pm

0.75000000

9:00:00 pm

0.87500000

10:30:00 pm

0.93750000

Entering times

As with entering dates, you normally don't have to worry about the actual time serial numbers. Just enter the time into a cell using a recognized format. Table 12.3 shows some examples of time formats that Excel recognizes.

Table 12.3 Time Entry Formats Recognized by Excel

Entry

Excel Interpretation

11:30:00 am

11:30 am

11:30:00 am

11:30 am

11:30 pm

11:30 pm

11:30

11:30 am

13:30

1:30 pm

Because the preceding samples don't have a specific day associated with them, Excel uses a date serial number of 0, which corresponds to the nonday January 0, 1900. Often, you'll want to combine a date and time. Do so by using a recognized date entry format, followed by a space, and then a recognized time entry format. For example, if you enter 6/18/2016 11:30 into a cell, Excel interprets it as 11:30 a.m. on June 18, 2016. Its date/time serial number is 42539.4791666667.

When you enter a time that exceeds 24 hours, the associated date for the time increments accordingly. For example, if you enter 25:00:00 into a cell, it's interpreted as 1:00 a.m. on January 1, 1900. The day part of the entry increments because the time exceeds 24 hours. Keep in mind that a time value without a date uses January 0, 1900, as the date.

Similarly, if you enter a date and a time (and the time exceeds 24 hours), the date that you entered is adjusted. If you enter 9/18/2016 25:00:00, for example, it's interpreted as 9/19/2016 1:00:00 a.m.

If you enter a time only (without an associated date) into an unformatted cell, the maximum time that you can enter into a cell is 9999:59:59 (just less than 10,000 hours). Excel adds the appropriate number of days. In this case, 9999:59:59 is interpreted as 3:59:59 p.m. on 02/19/1901. If you enter a time that exceeds 10,000 hours, the entry is interpreted as a text string rather than a time.

Formatting dates and times

You have a great deal of flexibility in formatting cells that contain dates and times. For example, you can format the cell to display the date part only, the time part only, or both the date and time parts.

You format dates and times by selecting the cells and then using the Number tab of the Format Cells dialog box, shown in Figure 12.1. To display this dialog box, click the dialog box launcher icon in the Number group of the Home tab, or click the Number Format control and choose More Number Formats from the list that appears.

Number tab of Format Cells dialog box presenting the selected Date category (left pane) and a highlighted *Wednesday, March 14, 2012 option in the Type menu (right pane).

Figure 12.1 Use the Number tab of the Format Cells dialog box to change the appearance of dates and times.

The Date category shows built-in date formats, and the Time category shows built-in time formats. Some formats include both date and time displays. Just select the desired format from the Type list, and then click OK.

Tip

When you create a formula that refers to a cell containing a date or a time, Excel sometimes automatically formats the formula cell as a date or a time. Often, this automation is helpful; other times, it's completely inappropriate and downright annoying. To return the number formatting to the default General format, choose Home image Number image Number Format and choose General from the drop-down list. Or just press Ctrl+Shift+˜ (tilde).

If none of the built-in formats meets your needs, you can create a custom number format. Select the Custom category and then type the custom format codes into the Type box.

imageSee Chapter 25, “Using Custom Number Formats,” for information on creating custom number formats.

Problems with dates

Excel has some problems when it comes to dates.` Many of these problems stem from the fact that Excel was designed many years ago. Excel designers basically emulated the Lotus 1-2-3 program's limited date and time features, which contain a nasty bug that was duplicated intentionally in Excel (described next). If Excel were being designed from scratch today, I'm sure it would be much more versatile in dealing with dates. Unfortunately, users are currently stuck with a product that leaves much to be desired in the area of dates.

Excel's leap year bug

A leap year, which occurs every four years, contains an additional day (February 29). Specifically, years that are evenly divisible by 100 are not leap years, unless they are also evenly divisible by 400. Although the year 1900 was not a leap year, Excel treats it as such. In other words, when you type 2/29/1900 into a cell, Excel interprets it as a valid date and assigns a serial number of 60.

If you type 2/29/1901, however, Excel correctly interprets it as a mistake and doesn't convert it to a date. Instead, it simply makes the cell entry a text string.

How can a product used daily by millions of people contain such an obvious bug? The answer is historical. The original version of Lotus 1-2-3 contained a bug that caused it to treat 1900 as a leap year. When Excel was released some time later, the designers knew about this bug and chose to reproduce it in Excel to maintain compatibility with Lotus worksheet files.

Why does this bug still exist in later versions of Excel? Microsoft asserts that the disadvantages of correcting this bug outweigh the advantages. If the bug were eliminated, it would mess up millions of existing workbooks. In addition, correcting this problem would possibly affect compatibility between Excel and other programs that use dates. As it stands, this bug really causes very few problems because most users don't use dates prior to March 1, 1900.

Pre-1900 dates

The world, of course, didn't begin on January 1, 1900. People who use Excel to work with historical information often need to work with dates before January 1, 1900. Unfortunately, the only way to work with pre-1900 dates is to enter the date into a cell as text. For example, you can enter July 4, 1776 into a cell, and Excel won't complain.

Tip

If you plan to sort information by old dates, you should enter your text dates with a four-digit year, followed by a two-digit month, and then a two-digit day — for example, 1776-07-04. You won't be able to work with these text strings as dates, but this format will enable accurate sorting.

Using text as dates works in some situations, but the main problem is that you can't perform manipulation on a date that's entered as text. For example, you can't change its numeric formatting, you can't determine which day of the week this date occurred on, and you can't calculate the date that occurs seven days later.

imageThe website for this book, www.wiley.com/go/excel2016bible, contains a workbook named XDATE demo.xlsm (plus a companion file named XDATE help.pdf). The workbook contains eight custom worksheet functions that I wrote in VBA. You will need to enable macros when you open this workbook. These functions enable you to work with any date in the years 0100 through 9999. Figure 12.2 shows a worksheet that uses these extended date functions in columns E through G to perform calculations that involve pre-1900 dates.

Image described by caption and surrounding text.

Figure 12.2 My Extended Date Functions add-in enables you to work with pre-1900 dates.

Inconsistent date entries

You need to be careful when entering dates by using two digits for the year. When you do so, Excel has some rules that determine which century to use.

Two-digit years between 00 and 29 are interpreted as 21st-century dates, and two-digit years between 30 and 99 are interpreted as 20th-century dates. For example, if you enter 12/15/28, Excel interprets your entry as December 15, 2028. But if you enter12/15/30, Excel sees it as December 15, 1930, because Windows uses a default boundary year of 2029. You can keep the default as is or change it via the Windows Control Panel. From the Regional and Language Options dialog box, click the Customize button to display the Customize Regional Options dialog box. Select the Date tab and then specify a different year.

Tip

The best way to avoid any surprises is to simply enter all years using all four digits for the year.

Date-Related Worksheet Functions

Excel has quite a few functions that work with dates. These functions are accessible by choosing Formulas image Function Library image Date & Time.

Table 12.4 summarizes the date-related functions available in Excel.

Table 12.4 Date-Related Functions

Function

Description

DATE

Returns the serial number of a particular date.

DATEVALUE

Converts a date in the form of text to a serial number.

DAY

Converts a serial number to a day of the month.

DAYS***

Returns the number of days between two dates.

DAYS360

Calculates the number of days between two dates based on a 360-day year.

EDATE*

Returns the serial number of the date that represents the indicated number of months before or after the start date.

EOMONTH*

Returns the serial number of the last day of the month before or after a specified number of months.

ISOWEEKNUM***

Returns the ISO week number for a date.

MONTH

Converts a serial number to a month.

NETWORKDAYS*

Returns the number of whole work days between two dates.

NETWORKDAYS.INTL**

Returns the number of whole work days between two dates. This is an international version of the NETWORKDAYS function that allows nonstandard weekend days.

NOW

Returns the serial number of the current date and time.

TODAY

Returns the serial number of today's date.

WEEKDAY

Converts a serial number to a day of the week.

WEEKNUM*

Returns the week number in the year.

WORKDAY*

Returns the serial number of the date before or after a specified number of workdays.

WORKDAY.INTL**

Returns the serial number of the date before or after a specified number of workdays. This is an international version of the WORKDAY function that allows nonstandard weekend days.

YEAR

Converts a serial number to a year.

YEARFRAC*

Returns the number of years, including the fraction, between start_date and end_date.

* In versions prior to Excel 2007, these functions are available only when the Analysis ToolPak add-in is installed.

** Indicates a function introduced in Excel 2010.

*** Indicates a function introduced in Excel 2013.

Displaying the current date

The following formula uses the TODAY function to display the current date in a cell:

=TODAY()

You can also display the date combined with text. The formula that follows, for example, displays text, such as Today is Saturday, April 9, 2016:

="Today is "&TEXT(TODAY(),"dddd, mmmm d, yyyy")

It's important to understand that the TODAY function is not a date stamp. The function is updated whenever the worksheet is calculated. For example, if you enter either of the preceding formulas into a worksheet, the formulas display the current date. And when you open the workbook tomorrow, they will display the current date (not the date when you entered the formula).

Tip

To enter a date stamp into a cell, press Ctrl+; (semicolon). This action enters the date directly into the cell and doesn't use a formula. Therefore, the date won't change.

Displaying any date

You can easily enter a date into a cell by simply typing it while using any of the date formats that Excel recognizes. You can also create a date by using the DATE function, which takes three arguments: the year, the month, and the day. The following formula, for example, returns a date comprising the year in cell A1, the month in cell B1, and the day in cell C1:

=DATE(A1,B1,C1)

Tip

The DATE function accepts invalid arguments and adjusts the result accordingly. For example, the following formula uses 13 as the month argument and returns January 1, 2016. The month argument is automatically translated as month 1 of the following year:

=DATE(2015,13,1)

Often, you'll use the DATE function with other functions as arguments. For example, the following formula uses the YEAR and TODAY functions to return the date for July 4 of the current year:

=DATE(YEAR(TODAY()),7,4)

The DATEVALUE function converts a text string that looks like a date into a date serial number. The following formula returns 42604, which is the date serial number for August 22, 2016:

=DATEVALUE("8/22/2016")

To view the result of this formula as a date, you need to apply a date number format to the cell.

Caution

Be careful when using the DATEVALUE function. A text string that looks like a date in your country may not look like a date in another country. The preceding example works fine if your system is set for U.S. date formats, but it returns an error for other regional date formats because Excel is looking for the 8th day of the 22nd month!

Generating a series of dates

Often, you want to insert a series of dates into a worksheet. For example, in tracking weekly sales, you may want to enter a series of dates, each separated by seven days. These dates will serve to identify the sales figures.

In some cases, you can use the Excel AutoFill feature to insert a series of dates. Enter the first date and drag the cell's fill handle while holding down the right mouse button. Release the mouse button and select an option from the shortcut menu (see Figure 12.3) — Fill Days, Fill Weekdays, Fill Months, or Fill Years. Notice that Excel does not provide a Fill Weeks option.

Worksheet presenting selected cells B1:B7 with input data (1/1/2016) on B1 and a right-click menu with a cursor pointing the Fill Weekdays option.

Figure 12.3 Using AutoFill to create a series of dates.

For more flexibility, enter the first two dates in the series — for example, the starting day for week 1 and the starting day for week 2. Then select both cells and drag the fill handle down the column. Excel will complete the date series, with each date separated by the interval represented by the first two dates.

Another way to create a series of dates is to use formulas. The advantage of using formulas (instead of AutoFill) to create a series of dates is that when you change the first date, the others update automatically. You need to enter the starting date in a cell and then use formulas (copied down the column) to generate the additional dates.

The following examples assume that you enter the first date of the series into cell A1 and the formula into cell A2. You can then copy this formula down the column as many times as needed.

To generate a series of dates separated by seven days, use this formula:

=A1+7

To generate a series of dates separated by one month, you need to use a more complicated formula because months don't all have the same number of days. This formula creates a series of dates, separated by one month:

=DATE(YEAR(A1),MONTH(A1)+1,DAY(A1))

To generate a series of dates separated by one year, use this formula:

=DATE(YEAR(A1)+1,MONTH(A1),DAY(A1))

To generate a series of weekdays only (no Saturdays or Sundays), use the following formula. This formula assumes that the date in cell A1 is not a weekend day.

=IF(WEEKDAY(A1)=6,A1+3,A1+1)

Converting a nondate string to a date

You may import data that contains dates coded as text strings. For example, the following text represents August 21, 2016 (a four-digit year followed by a two-digit month, followed by a two-digit day):

20160821

To convert this string to an actual date, you can use a formula such as the following to extract the three elements and convert them to a date. (This formula assumes that the coded data is in cell A1.)

=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))

This formula uses text functions (LEFT, MID, and RIGHT) to extract the digits, and then it uses these extracted digits as arguments for the DATE function.

imageSee Chapter 11, “Creating Formulas That Manipulate Text,” for more information about using formulas that deal with text.

Calculating the number of days between two dates

A common type of date calculation determines the number of days between two dates. For example, say you have a financial worksheet that calculates interest earned on a deposit account. The interest earned depends on the number of days the account is open. If your sheet contains the open date and the close date for the account, you can calculate the number of days the account was open.

Because dates are stored as consecutive serial numbers, you can use simple subtraction to calculate the number of days between two dates. For example, if cells A1 and B1 both contain a date, the following formula returns the number of days between these dates:

=A1-B1

If cell B1 contains a more recent date than the date in cell A1, the result will be negative. If you don't care about which date is earlier and want to avoid displaying a negative value, use this formula:

=ABS(A1-B1)

You can also use the DAYS worksheet function, which was introduced in Excel 2013. It offers no advantage that I can see, but here's an example of how to use it to calculate the number of days between two dates:

=DAYS(A1,B1)

Sometimes calculating the difference between two days is more difficult. To demonstrate, consider the common fence-post analogy. If somebody asks you how many units make up a fence, you can respond with either of two answers: the number of fence posts or the number of gaps between the fence posts. The number of fence posts is always one more than the number of gaps between the posts.

To bring this analogy into the realm of dates, suppose that you start a sales promotion on February 1 and end the promotion on February 9. How many days was the promotion in effect? Subtracting February 1 from February 9 produces an answer of eight days. Actually, though, the promotion lasted nine days. In this case, the correct answer involves counting the fence posts, not the gaps. The formula to calculate the length of the promotion (assuming that you have appropriately named cells) appears like this:

=EndDay-StartDay+1

Calculating the number of workdays between two dates

When calculating the difference between two dates, you may want to exclude weekends and holidays. For example, you may need to know how many business days fall in the month of November. This calculation should exclude Saturdays, Sundays, and holidays. TheNETWORKDAYS function can help out.

Note

In versions prior to Excel 2007, the NETWORKDAYS function was available only when the Analysis ToolPak add-in was installed. This function is now part of Excel and doesn't require an add-in. This is relevant if you plan to share your workbook with someone who uses an older version of Excel.

The NETWORKDAYS function calculates the difference between two dates, excluding weekend days (Saturdays and Sundays). As an option, you can specify a range of cells that contain the dates of holidays, which are also excluded. Excel has no way of determining which days are holidays, so you must provide this information in a range.

Figure 12.4 shows a worksheet that calculates the workdays between two dates. The range A2:A11 contains a list of holiday dates. The two formulas in column C calculate the workdays between the dates in column A and column B. For example, the formula in cell C15 is

=NETWORKDAYS(A15,B15,A2:A11)

Image described by caption and surrounding text.

Figure 12.4 Using the NETWORKDAYS function to calculate the number of workdays between two dates.

This formula returns 4, which means that the seven-day period beginning with January 1 contains four workdays. In other words, the calculation excludes one holiday, one Saturday, and one Sunday. The formula in cell C16 calculates the total number of workdays in the year and returns 252.

imageThis workbook is available on the book's website at www.wiley.com/go/excel2016bible. The file is named work days.xlsx.

Note

Excel 2010 introduced an updated version of the NETWORKDAYS function, named NETWORKDAYS.INTL. This newer version of the function is useful if you consider weekend days to be days other than Saturday and Sunday.

Offsetting a date using only workdays

The WORKDAY function is the opposite of the NETWORKDAYS function. For example, if you start a project on January 5 and the project requires twelve working days to complete, the WORKDAY function can calculate the date you will finish the project.

Note

In versions prior to Excel 2007, the WORKDAY function was available only when the Analysis ToolPak add-in was installed. The function is now part of Excel and doesn't require an add-in.

The following formula uses the WORKDAY function to determine the date that is twelve working days from January 5, 2016. A workday consists of a weekday (Monday through Friday).

=WORKDAY("1/5/2016",12)

The formula returns a date serial number, which must be formatted as a date. The result is January 21, 2016. (Four weekend dates fall between January 5 and January 21.)

Caution

The preceding formula may return a different result, depending on your regional date setting. (The hard-coded date may be interpreted as May 1, 2016.) A better formula follows:

=WORKDAY(DATE(2016,1,5),12)

The second argument for the WORKDAY function can be negative. And, as with the NETWORKDAYS function, the WORKDAY function accepts an optional third argument (a reference to a range that contains a list of holiday dates).

Note

Excel 2010 introduced an updated version of the WORKDAY function, named WORKDAY.INTL. This newer version of the function is useful if you consider weekend days to be days other than Saturday and Sunday.

Calculating the number of years between two dates

The following formula calculates the number of years between two dates. This formula assumes that cells A1 and B1 both contain dates:

=YEAR(A1)-YEAR(B1)

This formula uses the YEAR function to extract the year from each date and then subtracts one year from the other. If cell B1 contains a more recent date than the date in cell A1, the result is negative.

Note that this function doesn't calculate full years. For example, if cell A1 contains 12/31/2015 and cell B1 contains 01/01/2016, the formula returns a difference of one year even though the dates differ by only one day. (See the next section for another way to calculate the number of full years.)

Calculating a person's age

A person's age indicates the number of full years that the person has been alive. The formula in the previous section (for calculating the number of years between two dates) won't calculate this value correctly. You can use two other formulas, however, to calculate a person's age.

The following formula returns the age of the person whose date of birth you enter into cell A1. This formula uses the YEARFRAC function:

=INT(YEARFRAC(TODAY(),A1,1))

Note

In versions prior to Excel 2007, the YEARFRAC function was available only when the Analysis ToolPak add-in was installed. The function is now part of Excel and does not require an add-in.

The following formula uses the DATEDIF function to calculate an age. (See the next sidebar, “Where's the DATEDIF Function?”)

=DATEDIF(A1,TODAY(),"Y")

Where's the DATEDIF Function?

One of Excel's mysteries is the DATEDIF function. You may notice that this function doesn't appear in the drop-down function list for the Date & Time category, nor does it appear in the Insert Function dialog box. Therefore, when you use this function, you must always enter it manually.

The DATEDIF function has its origins in Lotus 1-2-3, and Excel provides it for compatibility purposes.

DATEDIF is a handy function that calculates the number of days, months, or years between two dates. The function takes three arguments: start_date, end_date, and a code that represents the time unit of interest. Here's an example of a formula that uses the DATEDIF function. (It assumes cells A1 and A2 contain a date.) The formula returns the number of complete years between those two dates.

=DATEDIF(A1,A2,"y")

The following table displays valid codes for the third argument. (You must enclose the codes in quotation marks.)

Unit Code

Returns

"y"

The number of complete years in the period.

"m"

The number of complete months in the period.

"d"

The number of days in the period.

"md"

The difference between the days in start_date and end_date. The months and years of the dates are ignored.

"ym"

The difference between the months in start_date and end_date. The days and years of the dates are ignored.

"yd"

The difference between the days of start_date and end_date. The years of the dates are ignored.

The start_date argument must be earlier than the end_date argument or else the function returns an error.

Determining the day of the year

January 1 is the first day of the year, and December 31 is the last day. But what about all those days in between? The following formula returns the day of the year for a date stored in cell A1:

=A1-DATE(YEAR(A1),1,0)

Here's a similar formula that returns the day of the year for the current date:

=TODAY()-DATE(YEAR(TODAY()),1,0)

The following formula returns the number of days remaining in the year after a particular date (assumed to be in cell A1):

=DATE(YEAR(A1),12,31)-A1

Here's the formula modified to use the current date:

=DATE(YEAR(TODAY()),12,31)-TODAY()

When you enter either formula, Excel applies date formatting to the cell. You need to apply a nondate number format to view the result as a number.

To convert a particular day of the year (for example, the 90th day of the year) to an actual date in a specified year, use the following formula, which assumes that the year is stored in cell A1 and that the day of the year is stored in cell B1:

=DATE(A1,1,B1)

This formula takes advantage of the fact that the DATE function accepts invalid dates (such as the 90th day of January) and adjusts automatically. The 90th day of January is actually the 90th day of the year.

Determining the day of the week

The WEEKDAY function accepts a date argument and returns an integer between 1 and 7 that corresponds to the day of the week. The following formula, for example, returns 6 because the first day of the year 2016 falls on a Friday:

=WEEKDAY(DATE(2016,1,1))

The WEEKDAY function uses an optional second argument that specifies the day numbering system for the result. If you specify 2 as the second argument, the function returns 1 for Monday, 2 for Tuesday, and so on. If you specify 3 as the second argument, the function returns 0 for Monday, 1 for Tuesday, and so on.

Tip

You can also determine the day of the week for a cell that contains a date by applying a custom number format. A cell that uses the following custom number format displays the day of the week, spelled out:

dddd

Determining the week of the year

To determine the week of the year for a date, use the WEEKNUM function. The following function returns the week number for the data in cell A1:

=WEEKNUM(A1)

When you use the WEEKNUM function, you can specify a second optional argument to indicate the type of week numbering system you prefer. The second argument can be one of ten values, which are described in the Help system.

Note

Excel 2013 introduced a new function, ISOWEEKNUM. This function uses the algorithm from the International Organization for Standardization. It returns the same result as WEEKNUM with a second argument of 21.

Determining the date of the most recent Sunday

You can use the following formula to return the date for the previous Sunday. If the current day is a Sunday, the formula returns the current date:

=TODAY()-MOD(TODAY()-1,7)

To modify this formula to find the date of a day other than Sunday, change the 1 to a different number between 2 (for Monday) and 7 (for Saturday).

Determining the first day of the week after a date

This formula returns the specified day of the week that occurs after a particular date. For example, use this formula to determine the date of the first Monday after a particular date. The formula assumes that cell A1 contains a date and cell A2 contains a number between 1 and 7 (1 for Sunday, 2 for Monday, and so on).

=A1+A2-WEEKDAY(A1)+(A2<WEEKDAY(A1))*7

If cell A1 contains June 1, 2016 (a Wednesday) and cell A2 contains 2 (for Monday), the formula returns June 6, 2016. This is the first Monday following June 1, 2016.

Determining the nth occurrence of a day of the week in a month

You may need a formula to determine the date for a particular occurrence of a weekday. For example, suppose that your company payday falls on the second Friday of each month and you need to determine the paydays for each month of the year. The following formula makes this type of calculation:

=DATE(A1,A2,1)+A3-WEEKDAY(DATE(A1,A2,1))+(A4-(A3>=WEEKDAY(DATE(A1,A2,1))))*7

The formula in this section assumes that

· Cell A1 contains a year.

· Cell A2 contains a month.

· Cell A3 contains a day number (1 for Sunday, 2 for Monday, and so on).

· Cell A4 contains the occurrence number (for example, 2 to select the second occurrence of the weekday specified in cell A3).

If you use this formula to determine the date of the second Friday in November 2016, it returns November 11, 2016.

Note

If the value in cell A4 exceeds the number of the specified day in the month, the formula returns a date from a subsequent month. For example, if you attempt to determine the date of the fifth Friday in October 2016 (there is no such date), the formula returns the first Friday in November.

Calculating dates of holidays

Determining the date for a particular holiday can be tricky. Some, such as New Year's Day and Independence Day in the United States, are no-brainers because they always occur on the same date. For these kinds of holidays, you can simply use the DATE function. To enter New Year's Day (which always falls on January 1) for a specific year in cell A1, you can enter this function:

=DATE(A1,1,1)

Other holidays are defined in terms of a particular occurrence of a particular weekday in a particular month. For example, Labor Day falls on the first Monday in September.

Figure 12.5 shows a workbook with formulas that calculate the date for 11 U.S. holidays. The formulas, which reference the year in cell A1, are listed in the sections that follow.

imageThe workbook shown in Figure 12.5 also appears on the companion website, at www.wiley.com/go/excel2016bible. The file is named holidays.xlsx.

Image described by surrounding text.

Figure 12.5 Using formulas to determine the date for various holidays.

New Year's Day

This holiday always falls on January 1:

=DATE(A1,1,1)

Martin Luther King, Jr., Day

This holiday occurs on the third Monday in January. This formula calculates Martin Luther King, Jr., Day for the year in cell A1:

=DATE(A1,1,1)+IF(2<WEEKDAY(DATE(A1,1,1)),7-WEEKDAY(DATE(A1,1,1))+2,

2-WEEKDAY(DATE(A1,1,1)))+((3-1)*7)

Presidents' Day

Presidents' Day occurs on the third Monday in February. This formula calculates Presidents' Day for the year in cell A1:

=DATE(A1,2,1)+IF(2<WEEKDAY(DATE(A1,2,1)),7-WEEKDAY(DATE(A1,2,1))+2,

2-WEEKDAY(DATE(A1,2,1)))+((3-1)*7)

Easter

Calculating the date for Easter is difficult because of the complicated manner in which Easter is determined. Easter Day is the first Sunday after the next full moon occurs after the vernal equinox. I found these formulas to calculate Easter on the Web. I have no idea how they work. And they don't work if your workbook uses the 1904 date system. (Read about the difference between the 1900 and 1904 date systems earlier in this chapter.)

=DOLLAR(("4/"&A1)/7+MOD(19*MOD(A1,19)-7,30)*14%,)*7-6

This one is slightly shorter, but equally obtuse:

=FLOOR("5/"&DAY(MINUTE(A1/38)/2+56)&"/"&A1,7)-34

Memorial Day

The last Monday in May is Memorial Day. This formula calculates Memorial Day for the year in cell A1:

=DATE(A1,6,1)+IF(2<WEEKDAY(DATE(A1,6,1)),7-WEEKDAY(DATE(A1,6,1))+2,

2-WEEKDAY(DATE(A1,6,1)))+((1-1)*7)-7

Notice that this formula actually calculates the first Monday in June and then subtracts 7 from the result to return the last Monday in May.

Independence Day

This holiday always falls on July 4:

=DATE(A1,7,4)

Labor Day

Labor Day occurs on the first Monday in September. This formula calculates Labor Day for the year in cell A1:

=DATE(A1,9,1)+IF(2<WEEKDAY(DATE(A1,9,1)),7-WEEKDAY(DATE(A1,9,1))+2,

2-WEEKDAY(DATE(A1,9,1)))+((1-1)*7)

Columbus Day

This holiday occurs on the second Monday in October. This formula calculates Columbus Day for the year in cell A1:

=DATE(A1,10,1)+IF(2<WEEKDAY(DATE(A1,10,1)),7-WEEKDAY(DATE(A1,10,1))+2,2-WEEKDAY(DATE(A1,10,1)))+((2-1)*7)

Veterans Day

This holiday always falls on November 11:

=DATE(A1,11,11)

Thanksgiving Day

Thanksgiving Day is celebrated on the fourth Thursday in November. This formula calculates Thanksgiving Day for the year in cell A1:

=DATE(A1,11,1)+IF(5<WEEKDAY(DATE(A1,11,1)),7-WEEKDAY(DATE(A1,11,1))+5,5-WEEKDAY(DATE(A1,11,1)))+((4-1)*7)

Christmas Day

This holiday always falls on December 25:

=DATE(A1,12,25)

Determining the last day of a month

To determine the date that corresponds to the last day of a month, you can use the DATE function. However, you need to increment the month by 1 and use a day value of 0. In other words, the “0th” day of the next month is the last day of the current month.

The following formula assumes that a date is stored in cell A1. The formula returns the date that corresponds to the last day of the month.

=DATE(YEAR(A1),MONTH(A1)+1,0)

You can use a variation of this formula to determine how many days are in a specified month. The following formula returns an integer that corresponds to the number of days in the month for the date in cell A1:

=DAY(DATE(YEAR(A1),MONTH(A1)+1,0))

Determining whether a year is a leap year

To determine whether a particular year is a leap year, you can write a formula that determines whether the 29th day of February occurs in February or March. You can take advantage of the fact that the Excel DATE function adjusts the result when you supply an invalid argument — for example, a day of 29 when February contains only 28 days.

The following formula returns TRUE if the year in cell A1 is a leap year. Otherwise, it returns FALSE:

=IF(MONTH(DATE(A1,2,29))=2,TRUE,FALSE)

Caution

This function returns the wrong result (TRUE) if the year is 1900. (See “Excel's leap year bug,” earlier in this chapter.)

The following formula is a bit more complicated, but it correctly identifies 1900 as a ­non-leap year. This formula assumes that cell A1 contains a year:

=IF(OR(MOD(A1,400)=0,AND(MOD(A1,4)=0,MOD(A1,100)<>0)),TRUE, FALSE)

Determining a date's quarter

For financial reports, you may find it useful to present information in terms of quarters. The following formula returns an integer between 1 and 4 that corresponds to the calendar quarter for the date in cell A1:

=ROUNDUP(MONTH(A1)/3,0)

This formula divides the month number by 3 and then rounds up the result.

Time-Related Worksheet Functions

Excel also includes a number of functions that enable you to work with time values in your formulas. This section contains examples that demonstrate the use of these functions.

Table 12.5 summarizes the time-related functions available in Excel. These functions work with date serial numbers. When you use the Insert Function dialog box, these functions appear in the Date & Time function category.

Table 12.5 Time-Related Functions

Function

Description

HOUR

Returns the hour part of a serial number

MINUTE

Returns the minute part of a serial number

NOW

Returns the serial number of the current date and time

SECOND

Returns the second part of a serial number

TIME

Returns the serial number of a specified time

TIMEVALUE

Converts a time in the form of text to a serial number

Displaying the current time

This formula displays the current time as a time serial number (or as a serial number without an associated date):

=NOW()-TODAY()

You need to format the cell with a time format to view the result as a recognizable time. The quickest way is to choose HomeimageNumberimageFormat Number and select Time from the drop-down list.

Or just use the following formula, which returns the current date and time. You can apply a number format that shows the time only:

=NOW()

Note

Formulas that use the NOW function are updated only when the worksheet is calculated. The time comes from your computer's clock, so if the clock is wrong, the formula will return an incorrect time.

Tip

To enter a time stamp (that doesn't change) into a cell, press Ctrl+Shift+: (colon).

Displaying any time

One way to enter a time value into a cell is to just type it, making sure that you include at least one colon (:). You can also create a time by using the TIME function. For example, the following formula returns a time comprising the hour in cell A1, the minute in cell B1, and the second in cell C1:

=TIME(A1,B1,C1)

Like the DATE function, the TIME function accepts invalid arguments and adjusts the result accordingly. For example, the following formula uses 80 as the minute argument and returns 10:20:15 AM. The 80 minutes are simply added to the hour, with 20 minutes remaining.

=TIME(9,80,15)

Caution

If you enter a value greater than 24 as the first argument for the TIME function, the result may not be what you expect. Logically, a formula such as the one that follows should produce a date/time serial number of 1.041667 (that is, one day and one hour).

=TIME(25,0,0)

In fact, this formula is equivalent to the following:

=TIME(1,0,0)

You can also use the DATE function along with the TIME function in a single cell. The formula that follows generates a date and time with a serial number of 42708.7708333333 — which represents 6:30 p.m. on December 4, 2016:

=DATE(2016,12,4)+TIME(18,30,0)

The TIMEVALUE function converts a text string that looks like a time into a time serial number. This formula returns 0.2395833333, the time serial number for 5:45 a.m.:

=TIMEVALUE("5:45 am")

To view the result of this formula as a time, you need to apply number formatting to the cell. The TIMEVALUE function doesn't recognize all common time formats. For example, the following formula returns an error because Excel doesn't like the ­periods in “a.m.”

=TIMEVALUE("5:45 a.m.")

Calculating the difference between two times

Because times are represented as serial numbers, you can subtract the earlier time from the later time to get the difference. For example, if cell A2 contains 5:30:00 and cell B2 contains 14:00:00, the following formula returns 08:30:00 (a difference of 8 hours and 30 minutes):

=B2-A2

If the subtraction results in a negative value, however, it becomes an invalid time; Excel displays a series of hash marks (#######) because a time without a date has a date serial number of 0. A negative time results in a negative serial number, which cannot be displayed — although you can still use the calculated value in other formulas.

If the direction of the time difference doesn't matter, you can use the ABS function to return the absolute value of the difference:

=ABS(B2-A2)

This “negative time” problem often occurs when calculating an elapsed time — for example, calculating the number of hours worked given a start time and an end time. This presents no problem if the two times fall in the same day. But if the work shift spans midnight, the result is an invalid negative time. For example, you may start work at 10:00 p.m. and end work at 6:00 a.m. the next day. Figure 12.6 shows a worksheet that calculates the hours worked. As you can see, the shift that spans midnight presents a problem (cell C3).

Image described by caption and surrounding text.

Figure 12.6 Calculating the number of hours worked returns an error if the shift spans midnight.

Using the ABS function (to calculate the absolute value) isn't an option in this case because it returns the wrong result (16). The following formula, however, does work:

=IF(B2<A2,B2+1,B2)-A2

Tip

Negative times are permitted if the workbook uses the 1904 date system. To switch to the 1904 date system, use the Advanced section of the Excel Options dialog box. Select the Use 1904 Date System option. But beware! When changing the workbook's date system, if the workbook uses dates, the dates will be off by four years. (For more ­information about the 1904 date system, see the sidebar “Choose Your Date System: 1900 or 1904,” earlier in this chapter.)

Summing times that exceed 24 hours

Many people are surprised to discover that when you sum a series of times that exceed 24 hours, Excel doesn't display the correct total. Figure 12.7 shows an example. The range B2:B8 contains times that represent the hours and minutes worked each day. The formula in cell B9 is

=SUM(B2:B8)

Image described by caption and surrounding text.

Figure 12.7 Incorrect cell formatting makes the total appear incorrectly.

As you can see, the formula returns a seemingly incorrect total (17 hours, 45 minutes). The total should read 41 hours, 45 minutes. The problem is that the formula is displaying the total as a date/time serial number of 1.7395833, but the cell formatting is not displaying the date part of the date/time. In other words, the answer is correct, but it appears incorrect because cell B9 has the wrong number format.

To view a time that exceeds 24 hours, you need to apply a custom number format for the cell so that square brackets surround the hour part of the format string. Applying the number format here to cell B9 displays the sum correctly:

[h]:mm

imageFor more information about custom number formats, see Chapter 25.

Figure 12.8 shows another example of a worksheet that manipulates times. This worksheet keeps track of hours worked during a week (regular hours and overtime hours).

Image described by caption and surrounding text.

Figure 12.8 An employee timesheet workbook.

imageThis workbook is available on this book's website at www.wiley.com/go/excel2016bible. The filename is timesheet.xlsm. The workbook contains a few macros to make it easier to use, so you'll need to enable macros when you open the workbook.

The week's starting date appears in cell D5, and the formulas in column B fill in the dates for the days of the week. Times appear in the range D8:G14, and formulas in column H calculate the number of hours worked each day. For example, the formula in cell H8 is

=IF(E8<D8,E8+1-D8,E8-D8)+IF(G8<F8,G8+1-G8,G8-F8)

The first part of this formula subtracts the time in column D from the time in column E to get the total hours worked before lunch. The second part subtracts the time in column F from the time in column G to get the total hours worked after lunch. I use IF functions to accommodate graveyard shift cases that span midnight — for example, an employee may start work at 10:00 p.m. and begin lunch at 2:00 a.m. Without the IF function, the formula returns a negative result.

The following formula in cell H17 calculates the weekly total by summing the daily totals in column H:

=SUM(H8:H14)

This worksheet assumes that hours in excess of 40 in a week are considered overtime. The worksheet contains a cell named Overtime in cell C23. This cell contains a formula that returns 40:00. If your standard workweek consists of something other than 40 hours, you can change this cell.

The following formula (in cell H18) calculates regular (nonovertime) hours. This formula returns the smaller of two values: the total hours or the overtime hours:

=MIN(E17,Overtime)

The final formula, in cell H19, simply subtracts the regular hours from the total hours to yield the overtime hours:

=E17-E18

The times in the range H17:H19 and cell C23 may display time values that exceed 24 hours, so these cells use a custom number format:

[h]:mm

Converting from military time

Military time is expressed as a four-digit number from 0000 to 2359. For example, 1:00 a.m. is expressed as 0100 hours, and 3:30 p.m. is expressed as 1530 hours. The following formula converts such a number (assumed to be in cell A1) to a standard time:

=TIMEVALUE(LEFT(A1,2)&":"&RIGHT(A1,2))

The formula returns an incorrect result if the contents of cell A1 do not contain four digits. The following formula corrects the problem, and it returns a valid time for any military time value from 0 to 2359:

=TIMEVALUE(LEFT(TEXT(A1,"0000"),2)&":"&RIGHT(A1,2))

Following is a simpler formula that uses the TEXT function to return a formatted string and then the TIMEVALUE function to express the result in terms of a time:

=TIMEVALUE(TEXT(A1,"00\:00"))

Converting decimal hours, minutes, or seconds to a time

To convert decimal hours to a time, divide the decimal hours by 24. For example, if cell A1 contains 9.25 (representing hours), this formula returns 09:15:00 (9 hours, 15 minutes):

=A1/24

To convert decimal minutes to a time, divide the decimal minutes by 1,440 (the number of minutes in a day). For example, if cell A1 contains 500 (representing minutes), the ­following formula returns 08:20:00 (8 hours, 20 minutes):

=A1/1440

To convert decimal seconds to a time, divide the decimal seconds by 86,400 (the number of seconds in a day). For example, if cell A1 contains 65,000 (representing seconds), the ­following formula returns 18:03:20 (18 hours, 3 minutes, and 20 seconds):

=A1/86400

Adding hours, minutes, or seconds to a time

You can use the TIME function to add any number of hours, minutes, or seconds to a time. For example, assume that cell A1 contains a time. The following formula adds 2 hours and 30 minutes to that time and displays the result:

=A1+TIME(2,30,0)

You can use the TIME function to fill a range of cells with incremental times. Figure 12.9 shows a worksheet with a series of times in ten-minute increments. Cell A1 contains a time that was entered directly. Cell A2 contains the following formula, which was copied down the column:

=A1+TIME(0,10,0)

Image described by surrounding text.

Figure 12.9 Using a formula to create a series of incremental times.

Rounding time values

You may need to create a formula that rounds a time to a particular value. For example, you may need to enter your company's time records rounded to the nearest 15 minutes. This section presents examples of various ways to round a time value.

The following formula rounds the time in cell A1 to the nearest minute:

=ROUND(A1*1440,0)/1440

The formula works by multiplying the time by 1,440 (to get total minutes). This value is passed to the ROUND function, and the result is divided by 1,440. For example, if cell A1 contains 11:52:34, the formula returns 11:53:00.

The following formula resembles this example, except that it rounds the time in cell A1 to the nearest hour:

=ROUND(A1*24,0)/24

If cell A1 contains 5:21:31, the formula returns 5:00:00.

The following formula rounds the time in cell A1 to the nearest 15 minutes (a quarter of an hour):

=ROUND(A1*24/0.25,0)*(0.25/24)

In this formula, 0.25 represents the fractional hour. To round a time to the nearest 30 minutes, change 0.25 to 0.5, as in the following formula:

=ROUND(A1*24/0.5,0)*(0.5/24)

Working with non-time-of-day values

Sometimes you may want to work with time values that don't represent an actual time of day. For example, you may want to create a list of the finish times for a race or record the amount of time you spend in meetings each day. Such times don't represent a time of day. Instead, a value represents the time for an event (in hours, minutes, and seconds). The time to complete a test, for example, may be 35 minutes and 45 seconds. You can enter that value into a cell as follows:

00:35:45

Excel interprets such an entry as 12:35:45 a.m., which works fine. (Just make sure that you format the cell so that it appears as you like.) When you enter such times, which don't have an hour component, you must include at least one zero for the hour. If you omit a leading zero for a missing hour, Excel interprets your entry as 35 hours and 45 minutes.

Figure 12.10 shows an example of a worksheet set up to keep track of a person's jogging activity. Column A contains simple dates. Column B contains the distance in miles. Column C contains the time it took to run the distance. Column D contains formulas to calculate the speed in miles per hour. For example, the formula in cell D2 is

=B2/(C2*24)

Image described by caption and surrounding text.

Figure 12.10 This worksheet uses times not associated with a time of day.

Column E contains formulas to calculate the pace, in minutes per mile. For example, the formula in cell E2 is

=(C2*60*24)/B2

Columns F and G contain formulas that calculate the year-to-date distance (using column B) and the cumulative time (using column C). The cells in column G are formatted using the following number format (which permits time displays that exceed 24 hours):

[hh]:mm:ss

imageYou can also access the workbook shown in Figure 12.10 on this book's website at www.wiley.com/go/excel2016bible. The file is named jogging log.xlsx.