Calculations in excel with time

Add time

Suppose that you want to know how many hours and minutes it will take to complete two tasks. You estimate that the first task will take 6 hours and 45 minutes and the second task will take 9 hours and 30 minutes.

Here is one way to set this up in the a worksheet.

  1. Enter 6:45 in cell B2, and enter 9:30 in cell B3.

  2. In cell B4, enter =B2+B3 and then press Enter.

    Time for two tasks added up

    The result is 16:15—16 hours and 15 minutes—for the completion the two tasks.

    Tip: You can also add up times by using the AutoSum function to sum numbers. Select cell B4, and then on the Home tab, choose AutoSum. The formula will look like this: =SUM(B2:B3). Press Enter to get the same result, 16 hours and 15 minutes.

Well, that was easy enough, but there’s an extra step if your hours add up to more than 24. You need to apply a special format to the formula result.

To add up more than 24 hours:

  1. In cell B2 type 12:45, and in cell B3 type 15:30.

  2. Type =B2+B3 in cell B4, and then press Enter.

    Time added up that's over 24 hours total an unexepcted result of 4:15

    The result is 4:15, which is not what you might expect. This is because the time for Task 2 is in 24-hour time. 15:30 is the same as 3:30.

  3. To display the time as more than 24 hours, select cell B4.

  4. On the Home tab, in the Cells group, choose Format, and then choose Format Cells.

    On the Home tab, Format button, and the Format cells button on the menu

  5. In the Format Cells box, choose Custom in the Category list.

  6. In the Type box, at the top of the list of formats, type [h]:mm;@ and then choose OK.

    Take note of the colon after [h] and a semicolon after mm.

The result is 28 hours and 15 minutes. The format will be in the Type list the next time you need it.

Subtract time

Here’s another example: Let’s say that you and your friends know both your start and end times at a volunteer project, and want to know how much time you spent in total.

Follow these steps to get the elapsed time—which is the difference between two times.

  1. In cell B2, enter the start time and include “a” for AM or “p” for PM. Then press Enter.

  2. In cell C2, enter the end time, including “a” or “p” as appropriate, and then press Enter.

  3. Type the other start and end times for your friends, Joy and Leslie.

  4. In cell D2, subtract the end time from the start time by entering the formula =C2-B2, and then press Enter.

    One time subtracted from another to get elapsed time

  5. In the Format Cells box, click Custom in the Category list.

  6. In the Type list, click h:mm (for hours and minutes), and then click OK.

    Now we see that Richard worked 3 hours and 45 minutes.

    Elpased times listed in column D

  7. To get the results for Joy and Leslie, copy the formula by selecting cell D2 and dragging to cell D4.

    The formatting in cell D2 is copied along with the formula.

To subtract time that’s more than 24 hours:

It is necessary to create a formula to subtract the difference between two times that total more than 24 hours.

Follow the steps below:

  1. Referring to the above example, select cell B1 and drag to cell B2 so that you can apply the format to both cells at the same time.

  2. In the Format Cells box, click Custom in the Category list.

  3. In the Type box, at the top of the list of formats, type m/d/yyyy h:mm AM/PM.

    Notice the empty space at the end of yyyy and at the end of mm.

    The new format will be available when you need it in the Type list.

  4. In cell B1, type the start date, including month/day/year and time using either “a” or “p” for AM and PM.

    Elapsed time over 24 hours

  5. In cell B2, do the same for the end date.

  6. In cell B3, type the formula =(B2-B1)*24.

The result is 31.5 hours.

Note: You can add and subtract more than 24 hours in Excel for the web but you cannot apply a custom number format.

Add time

Suppose you want to know how many hours and minutes it will take to complete two tasks. You estimate that the first task will take 6 hours and 45 minutes and the second task will take 9 hours and 30 minutes.

  1. In cell B2 type 6:45, and in cell B3 type 9:30.

  2. Type =B2+B3 in cell B4, and then press Enter.

Time for two tasks added up

It will take 16 hours and 15 minutes to complete the two tasks.

Tip: You can also add up times using AutoSum. Click in cell B4. Then click Home > AutoSum. The formula will look like this: =SUM(B2:B3). Press Enter to get the result, 16 hours and 15 minutes.

Subtract time

Say you and your friends know your start and end times at a volunteer project, and want to know how much time you spent. In other words, you want the elapsed time or the difference between two times.

  1. In cell B2 type the start time, enter a space, and then type “a” for AM or “p” for PM, and press Enter. In cell C2, type the end time, including “a” or “p” as appropriate, and press Enter. Type the other start and end times for your friends Joy and Leslie.

  2. In cell D2, subtract the end time from the start time by typing the formula: =C2-B2, and then pressing Enter. Now we see that Richard worked 3 hours and 45 minutes.

    One time subtracted from another to get elapsed time

  3. To get the results for Joy and Leslie, copy the formula by clicking in cell D2 and dragging to cell D4. The formatting in cell D2 is copied along with the formula.

    Elpased times listed in column D

Since dates and times are stored as numbers in the back end in Excel, you can easily use simple arithmetic operations and formulas on the date and time values.

For example, you can add two different time values or date values or you can calculate the time difference between two given dates/times.

In this tutorial, I will show you a couple of ways to perform calculations using time in Excel (such as calculating the time difference, adding or subtracting time, showing time in different formats, and doing a sum of time values)

How Excel Handles Date and Time?

As I mentioned, dates and times are stored as numbers in a cell in Excel. A whole number represents a complete day and the decimal part of a number would represent the part of the day (which can be converted into hours, minutes, and seconds values)

For example, the value 1 represents 01 Jan 1900 in Excel, which is the starting point from which Excel starts considering the dates.

So, 2 would mean 02 Jan 1990, 3 would mean 03 Jan 1900 and so on, and 44197 would mean 01 Jan 2021.

Note: Excel for Windows and Excel for Mac follow different starting dates. 1 in Excel for Windows would mean 1 Jan 1900 and 1 in Excel for Mac would mean 1 Jan 1904

If there are any digits after a decimal point in these numbers, Excel would consider those as part of the day and it can be converted into hours, minutes, and seconds.

For example, 44197.5 would mean 01 Jan 2021 12:00:00 PM.

Date and Time and its equivalent Numeric value

So if you’re working with time values in Excel, you would essentially be working with the decimal portion of a number.

And Excel gives you the flexibility to convert that decimal portion into different formats such as hours only, minutes only, seconds only, or a combination of hours, minutes, and seconds

Now that you understand how time is stored in Excel, let’s have a look at some examples of how to calculate the time difference between two different dates or times in Excel

Formulas to Calculating Time Difference Between Two Times

In many cases, all you want to do is find out the total time that has elapsed between the two-time values (such as in the case of a timesheet that has the In-time and the Out-time).

The method you choose would depend on how the time is mentioned in a cell and in what format you want the result.

Let’s have a look at a couple of examples

Simple Subtraction of Calculate Time Difference in Excel

Since time is stored as a number in Excel, find the difference between 2 time values, you can easily subtract the start time from the end time.

End Time – Start Time

The result of the subtraction would also be a decimal value that would represent the time that has elapsed between the two time-values.

Below is an example where I have the start and the end time and I have calculated the time difference with a simple subtraction.

Calculate time Difference with subtraction

There is a possibility that your results are shown in the time format (instead of decimals or in hours/minutes values). In our above example, the result in cell C2 shows 09:30 AM instead of 9.5.

That’s perfectly fine as Excel tries to copy the format from the adjacent column.

To convert this into a decimal, change the format of the cells to General (the option is in the Home tab in the Numbers group)

Once you have the result, you can format it in different ways. For example, you can show the value in hours only or minutes only or a combination of hours, minutes, and seconds.

Below are the different formats you can use:

Format What it Does
h Shows only the hours elapsed between the two dates
hh Shows hours in double-digit (such as 04 or 12)
hh:mm Shows hours and minutes elapsed between the two dates, such as 10:20
hh:mm:ss  Shows hours, minutes, and seconds elapsed between the two dates, such as 10:20:36

And if you’re wondering where and how to apply these custom date formats, follow the below steps:

  1. Select the cells where you want to apply the date format
  2. Hold the Control key and press the 1 key (or Command + 1 if using Mac)
  3. In the Format Cells dialog box that opens, click on the Number tab (if not selected already)Click the Number group
  4. In the left pane, click on CustomClick on Custom option in Format Cells dialog box
  5. Enter any of the desired format code in the Type field (in this example, I am using hh:mm:ss)Enter the code to show hour minutes and seconds
  6. Click OK

The above steps would change the formatting and show you the value based on the format.

Result of time difference calculation

Note that custom number formatting does not change the value in the cell. It only changes the way a value is being displayed. So, I can choose to only show the hour value in a cell, while it would still have the original value.

Pro tip: If the total number of hours exceeds 24 hours, use the following custom number format instead: [hh]:mm:ss

Calculate the Time Difference in Hours, Minutes, or Seconds

When you subtract the time values, Excel returns a decimal number that represents the resulting time difference.

Since every whole number represents one day, the decimal part of the number would represent that much part of the day which can easily be converted into hours or minutes, or seconds.

Calculating Time Difference in Hours

Suppose you have the dataset as shown below and you want to calculate the number of hours between the two-time values

Time difference where we need to calculate hours

Below is the formula that will give you the time difference in hours:

=(B2-A2)*24
Time difference in houts

The above formula will give you the total number of hours elapsed between the two-time values.

Sometimes, Excel tries to be helpful and will give you the result in time format as well (as shown below).

Time difference shown in the time format only

You can easily convert this into Number format by clicking on the Home tab, and in the Number group, selecting Number as the format.

Click the Number option in the format drop down

If you only want to return the total number of hours elapsed between the two times (without any decimal part), use the below formula:

=INT((B2-A2)*24)
Calculating hours elapsed between two times

Note: This formula only works when both the time values are of the same day. If the day changes (where one of the time values is of another date and the second one of another date), This formula will give wrong results. Have a look at the section where I cover the formula to calculate the time difference when the date changes later in this tutorial.

Calculating Time Difference in Minutes

To calculate the time difference in minutes, you need to multiply the resulting value by the total number of minutes in a day (which is 1440 or 24*60).

Suppose you have a data set as shown below and you want to calculate the total number of minutes elapsed between the start and the end date.

Time difference where we need to calculate hours

Below is the formula that will do that:

=(B2-A2)*24*60
Calculate Time difference in Minutes

Calculating Time Difference in Seconds

To calculate the time difference in seconds, you need to multiply the resulting value by the total number of seconds in a day (which is or 24*60*60 or 86400).

Suppose you have a data set as shown below and you want to calculate the total number of seconds that have elapsed between the start and end date.

Time difference where we need to calculate hours

Below is the formula that will do that:

=(B2-A2)*24*60*60
Calculate Time difference in seconds

Calculating time difference with the TEXT function

Another easy way to quickly get the time difference without worrying about changing the format is to use the TEXT function.

The TEXT function allows you to specify the format right within the formula.

=TEXT(End Date - Start Date, Format)

The first argument is the calculation you want to do, and the second argument is the format in which you want to show the result of the calculation.

Suppose you have a dataset as shown below and you want to calculate the time difference between the two times.

Time difference where we need to calculate hours

Here are some formulas that will give you the result with different formats

Show only the number of hours:

=TEXT(B2-A2,"hh")
Calculating Time in hours using TEXT Function

The above formula will only give you the result that shows the numbers of hours elapsed between the two-time values. If your result is 9 hours and 30 minutes, it will still show you 9 only.

Show the number of total minutes

=TEXT(B2-A2,"[mm]")
Calculating Time in Minutes using TEXT Function

Show the number of total seconds

=TEXT(B2-A2,"[ss]")
Calculating Time in Seconds using TEXT Function

Show Hours and Minutes

=TEXT(B2-A2,"[hh]:mm")
Time difference in hours and minutes

Show Hours, Minutes, and Seconds

=TEXT(B2-A2,"hh:mm:ss")
Time difference in hours minutes and Seconds

If you’re wondering what’s the difference between hh and [hh] in the format (or mm and [mm]), when you use the square brackets, it would give you the total number of hours between the two dates, even if the hour value is higher than 24. So if you subtract two date values where the difference is more than24 hours, using [hh] will give you the total number of hours and hh will only give you the hours elapsed on the day of the end date.

Get the Time Difference in One-Unit (Hours/Minutes) and Ignore Others

If you want to calculate the time difference between the two time-values in only the number of hours or minutes or seconds, then you can use the dedicated HOUR, MINUTE, or SECOND function.

Each of these functions takes one single argument, which is the time value, and returns the specified time unit.

Suppose you have a data set as shown below, and you want to calculate the total number of hours minutes, and seconds that have elapsed between these two times.

In and Out time dataset

Below are the formulas to do this:

Calculating Hours Elapsed Between two times

=HOUR(B2-A2)
HOUR formula

Calculating Minutes from the time value result (excluding the completed hours)

=MINUTE(B2-A2)
Minute formula

Calculating Seconds from the time value result (excluding the completed hours and minutes)

=SECOND(B2-A2)
Second formula

A couple of things that you need to know when working with these HOURS, MINUTE, and SECOND formulas:

  • The difference between the end time and the start time cannot be negative (which is often the case when the date changes). In such cases, these formulas would return a #NUM! error
  • These formulas only use the time portion of the resulting time value (and ignore the day portion). So if the difference in the end time and the start time is 2 Days, 10 Hours, 32 Minutes, and 44 Seconds, the HOUR formula will give 10, the MINUTE formula will give 32, and the SECOND formula will give 44

Calculate elapsed time Till Now (from the start time)

If you want to calculate the total time that has elapsed between the start time and the current time, you can use the NOW formula instead of the End time.

NOW function returns the current date and the time in the cell in which it is used. It’s one of those functions that does not take any input argument.

So, if you want to calculate the total time that has elapsed between the start time and the current time, you can use the below formula:

=NOW() - Start Time

Below is an example where I have the start times in column A, and the time elapsed till now in column B.

Calculating time elapsed till now

If the difference in time between the start date and time and the current time is more than 24 hours, then you can format the result to show the day as well as the time portion.

You can do that by using the below TEXT formula:

=TEXT(NOW()-A2,"dd hh:ss:mm")

You can also achieve the same thing by changing the custom formatting of the cell (as covered earlier in this tutorial) so that it shows the day as well as the time portion.

In case your start time only has the time portion, then Excel would consider it as the time on 1st January 1990.

In this case, if you use the NOW function to calculate the time elapsed till now, it is going to give you the wrong result (as the resulting value would also have the total days that have elapsed since 1st Jan 1990).

In such a case, you can use the below formula:

=NOW()- INT(NOW())-A2

The above formula uses the INT function to remove the day portion from the value returned by the now function, and this is then used to calculate the time difference.

Note that NOW is a volatile function that updates whenever there is a change in the worksheet, but it does not update in real-time

Calculate Time When Date Changes (calculate and display negative times in Excel)

The methods covered so far work well if your end time is later than the start time.

But the problem arises when your end time is lower than the start time. This often happens when you are filling timesheets where you only enter the time and not the entire date and time.

In such cases, if you’re working in a one night shift and the date changes, there is a possibility that your end time would be earlier than your start time.

For example, if you start your work at 6:00 PM in the evening, and complete your work & time out at 9:00 AM in the morning.

If you only working with time values, then subtracting the start time from the end time is going to give you a negative value of 9 hours (9 – 18).

And Excel cannot handle negative time values (and for that matter nor can humans, unless you can time travel)

In such cases, you need a way to figure out that the day has changed and the calculation should be done accordingly.

Thankfully, there is a really easy fix for this.

Suppose you have a dataset as shown below, where I have the start time and the end time.

In and out time on different dates

As you would notice that sometimes the start time is in the evening and the end time is in the morning (which indicates that this was an overnight shift and the day has changed).

If I use the below formula to calculate the time difference, it will show me the hash signs in the cells where the result is a negative value (highlighted in yellow in the below image).

=B2-A2
Showing hash instead of time elapsed

Here is an IF formula that whether the time difference value is negative or not, and in case it is negative then it returns the right result

=IF((B2-A2)<0,1-(A2-B2),(B2-A2))
Formula to calculate time when date changes

While this works well in most cases, it still falls short in case the start time and the end time is more than 24 hours apart. For example, someone signs in at 9:00 AM on day 1 and sign-out at 11:00 AM on day 2.

Since this is more than 24 hours, there is no way to know whether the person has signed out after 2 hours or after 26 hours.

While the best way to tackle this would be to make sure that the entries include the date as well as the time, but if it’s just the time that you’re working with, then the above formula should take care of most of the issues (considering it’s unlikely for anyone to work for more than 24 hours)

Adding/ Subtracting Time in Excel

So far, we have seen examples where we had the start and the end time, and we needed to find the time difference.

Excel also allows you to easily add or subtract a fixed time value from the existing date and time value.

For example, let’s say you have a list of queued tasks where each task takes the specified time, and you want to know when each task will end.

In such a case, you can easily add the time that each task is going to take to the start time to know at what time is the task expected to be completed.

Since Excel stores date and time values as numbers, you have to ensure that the time you are trying to add abides by the format that Excel already follows.

For example, if you add 1 to a date in Excel, it is going to give you the next date. This is because 1 represents an entire day in Excel (which is equal to 24 hours).

So if you want to add 1 hour to an existing time value, you cannot go ahead and simply add 1 to it. you have to make sure that you convert that hour value into the decimal portion that represents one hour. and the same goes for adding minutes and seconds.

Using the TIME Function

Time function in Excel takes the hour value, the minute value, and the seconds value and converts it into a decimal number that represents this time.

For example, if I want to add 4 hours to an existing time, I can use the below formula:

=Start Time + TIME(4,0,0)
Adding time using the TIME function

This is useful if you know how many hours, minutes, and seconds you want to add to an existing time and simply use the TIME function without worrying about the correct conversion of the time into a decimal value.

Also, note that the TIME function will only consider the integer part of the hour, minute, and seconds value that you input. For example, if I use 5.5 hours in the TIME function it would only add five hours and ignore the decimal part.

Also, note that the TIME function can only add values that are less than 24 hours. If your hour value is more than 24, this would give you an incorrect result.

And the same goes with the minutes and the second’s part where the function will only consider values that are less than 60 minutes and 60 seconds

Just like I have added time using the TIME function, you can also subtract time. Just change the + sign to a negative sign in the above formulas

Using Basic Arithmetic

When the time function is easy and convenient to use, it does come with a few restrictions (as covered above).

If you want more control, you can use the arithmetic method that I’ll cover here.

The concept is simple – convert the time value into a decimal value that represents the portion of the day, and then you can add it to any time value in Excel.

For example, if you want to add 24 hours to an existing time value, you can use the below formula:

=Start_time + 24/24

This just means that I’m adding one day to the existing time value.

Now taking the same concept forward let’s say you want to add 30 hours to a time value, you can use the below formula:

=Start_time + 30/24

The above formula does the same thing, where the integer part of the (30/24) would represent the total number of days in the time that you want to add, and the decimal part would represent the hours/minutes/seconds

Similarly, if you have a specific number of minutes that you want to add to a time value then you can use the below formula:

=Start_time + (Minutes to Add)/24*60

And if you have the number of seconds that you want to add, then you can use the below formula:

=Start_time + (Minutes to Add)/24*60*60

While this method is not as easy as using the time function, I find it a lot better because it works in all situations and follows the same concept. unlike the time function, you don’t have to worry about whether the time that you want to add is less than 24 hours or more than 24 hours

You can follow the same concept while subtracting time as well. Just change the + to a negative sign in the formulas above

How to SUM time in Excel

Sometimes you may want to quickly add up all the time values in Excel. Adding multiple time values in Excel is quite straightforward (all it takes is a simple SUM formula)

But there are a few things you need to know when you add time in Excel, specifically the cell format that is going to show you the result.

Let’s have a look at an example.

Below I have a list of tasks along with the time each task will take in column B, and I want to quickly add these times and know the total time it is going to take for all these tasks.

Activity and time taken data

In cell B9, I have used a simple SUM formula to calculate the total time all these tasks are going to take, and it gives me the value as 18:30 (which means that it is going to take 18 hours and 20 minutes to complete all these tasks)

Sum of time where sum is less than 24 hours

All good so far!

How to SUM over 24 hours in Excel

Now see what happens when I change at the time it is going to take Task 2 to complete from 1 hour to 10 hours.

SUM formula giving incorrect time value

The result now says 03:20, which means that it should take 3 hours and 20 minutes to complete all these tasks.

This is incorrect (obviously)

The problem here is not Excel messing up. The problem here is that the cell is formatted in such a way that it will only show you the time portion of the resulting value.

And since the resulting value here is more than 24 hours, Excel decided to convert the 24 hours part into a day remove it from the value that is shown to the user, and only display the remaining hours, minutes, and seconds.

This, thankfully, has an easy fix.

All you need to do is change the cell format to force it to show hours even if it exceeds 24 hours.

Below are some formats that you can use:

Format Expected Result
[h]:mm 28:30
[m]:ss 1710:00
d “D” hh:mm 1 D 04:30
d “D” hh “Min” ss “Sec” 1 D 04 Min 00 Sec
d “Day” hh “Minute” ss “Seconds” 1 Day 04 Minute 00 Seconds

You can change the format by going to the format cells dialog box and applying the custom format, or use the TEXT function and use any of the above formats in the formula itself

You can use the below the TEXT formula to show the time, even when it’s more than 24 hours:

=TEXT(SUM(B2:B7),"[h]:mm:ss")
TEXT formula to show hours when more than 24

or the below formula if you want to convert the hours exceeding 24 hours to days:

=TEXT(SUM(B2:B7),"dd hh:mm:ss")
TEXT formula to show days in the time result

Results Showing Hash (###) Instead of Date/Time (Reasons + Fix)

In some cases, you may find that instead of showing you the time value, Excel is displaying the hash symbols in the cell.

Here are some possible reasons and the ways to fix these:

The column is not wide enough

When a cell doesn’t have enough space to show the complete date, it may show the hash symbols.

It has an easy fix – change the column width and make it wider.

Negative Date Value

A date or time value cannot be negative in Excel. in case you are calculating the time difference and it turns out to be negative, Excel will show you hash symbols.

The way to fixes to change the formula to give you the right result. For example, if you are calculating the time difference between the two times, and the date changes, you need to adjust the formula to account for it.

In other cases, you may use the ABS function to convert the negative time value into a positive number so that it’s displayed correctly. Alternatively, you can also an IF formula to check if the result is a negative value and return something more meaningful.

In this tutorial, I covered topics about calculating time in Excel (where you can calculate the time difference, add or subtract time, show time in different formats, and sum time values)

I hope you found this tutorial useful.

Other Excel tutorials you may also like:

  • Convert Time to Decimal Number in Excel (Hours, Minutes, Seconds)
  • How to Remove Time from Date/Timestamp in Excel
  • How to Calculate the Number of Days Between Two Dates in Excel
  • Combine Date and Time in Excel
  • How to Calculate Years of Service in Excel
  • How to Convert Seconds to Minutes in Excel

How to Calculate Time in Excel (A Complete Tutorial and Helpful Formulas)

If you’ve been relying on Excel to manage your projects and need help with time calculations, you’re not alone. Figuring out the elapsed time of a project or task is crucial for team leads that need to know what work should be prioritized and how to properly allocate resources.

Simply put, time values are tricky in Excel—especially when calculating time difference, hours worked, or the difference between two employees.

Luckily for you, we’ve done all the hard work to help format cells and calculate elapsed time in Excel faster. Let’s get confident about using Excel for project time tracking and discover the various ways of figuring time.

How to Calculate Time in Excel (A Complete Tutorial and Helpful Formulas)

Types of Time Calculations in Excel

There isn’t a single formula or format for calculating time in Excel. It depends on your dataset and the goal you want to achieve. Most use a custom format (number over text function) to understand time and date values, or the time difference value.

But there are two types of calculations to get you started, which include:

  • Add time: If you need to obtain the sum of two time values to get a total
    • Add up to less than 24 hours: When you need to know how many hours and minutes it’ll take to complete two simple tasks
    • Add up to more than 24 hours: When you need to add the estimated or actual elapsed time of multiple slow, complex tasks
  • Subtract time: If you need to get the total time between a start and end times
    • Subtract times whose difference is less than 24 hours: When you need to figure out the hours elapsed since a team member started to execute a simple task
    • Subtract times whose difference is more than 24 hours: When you need to know the hours that have gone by since your project started

Let’s go through a few formulas for time calculations in Excel so you get down to the exact hours, minutes, and seconds in your custom time format.

Time Difference in Excel

Before we teach you how to calculate time in Excel, you must understand what time values are in the first place. Time values are the decimal number to which Excel applied a time format to make them look like times (i.e., the hours, minutes, and seconds).

Because Excel times are numbers, you can add and subtract them. And the difference between a start time and an end time is called “time difference” or “elapsed time.”

These are the steps to subtract times whose difference is less than 24 hours:

1. Enter the start date and time in cell A2 and hit Enter. Don’t forget to write “AM” or “PM”
2. Enter the end time in cell B2 and hit Enter
3. Enter the formula =B2-A2 in cell C2 and hit Enter.

Same Day Time Format in Excel example
An example of subtracting time on the same day in Excel

WARNING
As you can tell from the figure, this formula doesn’t work for times that belong to different days. This example shows the time difference between two time values within a 24-hour time period.

4. Right-click on C2 and select Format Cells.

example of formatting Cells for time values in excel
The custom value can be set up in various date format options

5. Choose the Custom category and type “h:mm”

SIDE NOTE
You might wish to obtain the time difference expressed in hours or hours, minutes, and seconds. If so, type “h” or “h:mm:ss,” respectively. This will help you avoid negative time values.

6. Click OK to see the total change to a format describing only the number of hours and minutes in the elapsed time between A2 and B2.

Example format showing the number of hours and minutes
Example format showing the hours and minutes

Check out our detailed blog to find a list of time management strategies you can use right away!

Date and time in Excel

In the previous section, you learned how to calculate hours in Excel. But the formula you learned only applied to time differences of less than 24 hours.

If you need to subtract times whose difference is more than 24 hours, you need to work with dates besides times. Do it like this (format cells dialog box):

1. Enter the start time in cell A2 and hit Enter.
2. Enter the end time in cell B2 and hit Enter.
3. Right-click on A2 and select Format Cells.
4. Choose the Custom category and type “m/d/yyyy h:mm AM/PM.”
5. Click OK to see A2 change to a format starting with “1/0/1900” and adjust the date.
6. Use the Format Painter to copy the formatting of A2 to B2 and adjust the date.
7. Enter the formula =(B2-A2)*24 in cell C2 and hit Enter to see the total change to a format describing the number of hours in the time elapsed between A2 and B2.

Total Change to subtract times example in excel

Example of the total change to subtract times in Excel

WARNING
You must apply the “Number” format to C2 to get the correct value in the above formula.

Sum time in Excel

Suppose you want to sum up the time difference between your team members working on multiple project tasks. If those durations add up to less than 24 hours, follow these steps:

1. Enter one duration in cell B2 (with the format h:mm) and hit Enter.
2. Enter the other duration in cell B3 and hit Enter.
3. Enter the formula =B2+B3 in cell B4 and hit Enter.

Example of combining times that equal less than 24 hours
Example of combining times that equal less than 24 hours in Excel formulas (Column B)

PRO TIP
If you prefer clicking a single button instead of entering a formula, you may position the cursor in B4 and hit the Σ (or AutoSum) button in the Home tab. The button will apply the formula =SUM(B2:B3) to the cell in the above example.

If the total duration of your project tasks adds up to more than 24 hours, follow these steps instead:

1. Enter one duration in cell B2 (with the format h:mm) and hit Enter. (Warning: Beware that the maximum duration is 23 hours and 59 minutes)
2. Enter the other duration in cell B3 and hit Enter.
3. Enter the formula =B2+B3 in cell B4 and hit Enter.
4. Right-click on B4 and select Format Cells.
5. Choose the Custom category and type “[h]:mm;@.”
6. Click OK to see B4 correctly displaying the sum of the times in B2 and B3.

Example of combining times that equal more than 24 hours
Example of combining values that equals more than 24 hours (Column B)

If you’d like to know more about Excel project management, our blog is the perfect place to start!

The Complete List of Formulas for Calculating Time in Excel

It pays to know the formulas when you’re calculating time difference in Excel. To get your time difference and value set up correctly, we’ve provided a list of formulas to make your calculations easier.

Formula Description
=B2-A2 Difference between the two time values in cells A2 and B2
=(B2-A2)*24 Hours between the value in cells A2 and B2 (24 being the number of hours in a day)

 Warning: If the difference is 24+ hours, you must apply the “Custom” format with the type “m/d/yyyy h:mm AM/PM” to A2 and B2. You also must apply the “Number” format to the cell containing the time difference formula.

=TIMEVALUE(“8:02 PM”)-TIMEVALUE(“9:15 AM”) Warning: The difference must be less than 24 hours.
=TEXT(B2-A2,”h”) Hours between the values in cells A2 and B2

 Warning: You must apply the “Custom” format with the type “h” to A2 and B2. Also, the value in B2 cannot be less than A2 and the difference must be less than 24 hours to avoid a negative value. And the TEXT function returns a textual value.

=TEXT(B2-A2,”h:mm”) Minutes and hours between the time values in cells A2 and B2.

 Warning: You must apply the “Custom” format with the type “h:mm” to A2 and B2. Also, the value in B2 cannot be less than A2 and the difference must be less than 24 hours.

=TEXT(B2-A2,”h:mm:ss”) Hours, minutes, and seconds between the time values in cells A2 and B2.

 Warning: You must apply the “Custom” format with the type “h:mm:ss” to A2 and B2. And the value in B2 cannot be less than A2 and the difference must be less than 24 hours.

=INT((B2-A2)*24) Number of complete hours between the time values in cells A2 and B2 (24 being hours in a day).

 Warning: If the difference is 24+ hours, you must apply the “Custom” format with the type “m/d/yyyy h:mm AM/PM” to A2 and B2. And you must apply the “Number” format to the cell containing the time difference formula.

=(B2-A2)*1440 Minutes between the time values in cells A2 and B2 (1440 being minutes in a day).

Warning: If the difference is 24+ hours, you must apply the “Custom” format with the type “m/d/yyyy h:mm AM/PM” to A2 and B2. And you must apply the “Number” format to the cell containing the time difference formula.

=(B2-A2)*86400 Seconds between the time values in cells A2 and B2 (86400 being the seconds in a day).
 
Warning: If the difference is 24+ hours, you must apply the “Custom” format with the type “m/d/yyyy h:mm AM/PM” to A2 and B2. And you must apply the “Number” format to the cell containing the time difference formula.
=HOUR(B2-A2) Hours between the time values in cells A2 and B2.

Warning: The value in B2 cannot be less than the value in A2 and the difference must be less than 24 hours. Also, the HOUR function returns a numeric value.

=MINUTE(B2-A2) Minutes between the time values in cells A2 and B2.

 Warning: The value in B2 cannot be less than the value in A2 and the difference must be less than 60 minutes. Also, the MINUTE function returns a numeric value.

=SECOND(B2-A2) Seconds between the time values in cells A2 and B2.

 Warning: The value in B2 cannot be less than the value in A2 and the difference must be less than 60 seconds. Also, the SECOND function returns a numeric value.

=NOW()-A2 Time elapsed between the date and time in cell A2 and the current date and time.

 Warning: If the elapsed time is 24+ hours, you must apply the “Custom” format with the type “d “days” h:mm:ss” to the cell containing the time difference formula. Also, Excel doesn’t update the elapsed time in real-time. To do that, you must hit Shift+F9.

=TIME(HOUR(NOW()),MINUTE(NOW()),SECOND(NOW()))-A2 Time elapsed between the value in cell A2 and the current date and time.

 Warning: Excel doesn’t update the elapsed time in real-time. To do that, you must hit Shift+F9.

=INT(B2-A2)&” days, “&HOUR(B2-A2)&” hours, “&MINUTE(B2-A2)&” minutes, and “&SECOND(B2-A2)&” seconds” Time elapsed between the date and time or time values in cells A2 and B2, expressed in the format “dd days, hh hours, mm minutes, and ss seconds.”

 Warning: This formula returns a textual value. If you need the result to be a value, use the formula =B2-A2 and apply the “Custom” format with the type “d “days,” h “hours,” m “minutes, and” s “seconds”” to the cell containing the time difference formula.

=IF(INT(B2-A2)>0,INT(B2-A2)&” days,”,””)&IF(HOUR(B2-A2)>0,HOUR(B2-A2)&” hours,”,””)&IF(MINUTE(B2-A2)>0,MINUTE(B2-A2)&” minutes, and “,””)&IF(SECOND(B2-A2)>0,SECOND(B2-A2)&” seconds”,””) Time elapsed between the date and time or values in cells A2 and B2, expressed in the format “dd days, hh hours, mm minutes, and ss seconds” with zero values hidden.

 Warning: This formula returns a textual value. If you need the result to be a value, use the formula =B2-A2 and apply the “Custom” format with the type “d “days,” h “hours,” m “minutes, and” s “seconds”” to the cell containing the time difference formula.

=A2+TIME(1,0,0) Value in cell A2 plus one hour.

 Warning: This formula only allows adding less than 24 hours to a value.

=A2+(30/24) Value in cell A2 plus 30 hours (24 being hours in a day).

 Warning: This formula allows adding any number of hours to a value.

=A2-TIME(1,0,0) Time value in cell A2 minus one hour.

 Warning: This formula only allows subtracting less than 24 hours from a value.

=A2-(30/24) Time value in cell A2 minus 30 hours.

 Warning: This formula allows subtracting any number of hours from a value.

=A2+TIME(0,1,0) Time value in cell A2 plus one minute.

 Warning: This formula only allows adding less than 60 minutes to a value.

=A2+(100/1440) Time value in cell A2 plus 100 minutes (1440 being minutes in a day).

 Warning: This formula allows adding any number of minutes to a value.

=A2-TIME(0,1,0) Time value in cell A2 minus one minute.

 Warning: This formula only allows subtracting less than 60 minutes from a value.

=A2-(100/1440) Time value in cell A2 minus 100 minutes.

 Warning: This formula allows subtracting any number of minutes from a value.

=A2+TIME(0,0,1) Time value in cell A2 plus one second.

 Warning: This formula only allows adding less than 60 seconds to a value.

=A2+(100/86400) Time value in cell A2 plus 100 seconds (86400 being seconds in a day).

Warning: This formula allows adding any number of seconds to a value.

=A2-TIME(0,0,1) Time value in cell A2 minus one second.

 Warning: This formula only allows subtracting less than 60 seconds from a value.

=A2-(100/86400) Time value in cell A2 minus 100 seconds.

 Warning: This formula allows subtracting any number of seconds from a value.

=A2+B2

=SUM(A2:B2)

Total hours, hours and minutes, or hours, minutes, and seconds in the values from cells A2 and B2, depending on the format you applied to those cells.

 Warning: If the total adds up to more than 24 hours, you must apply the “Custom” format with the type “[h]:mm;@” to the cell containing the SUM formula.

An Easier Alternative to Calculating Time in Excel

Although the formulas in this article work, there’s a better way to calculate time—ClickUp!

Sure, spreadsheets are great for managing data, but what about your day-to-day tasks? And how do you communicate with your team to show these times in a simple and clear way?

Table view in ClickUp
Arrange all of your tasks on a grid alongside their key details including status, due date, assignees, and more with Table view in ClickUp

ClickUp’s Table view keeps track of all your tasks, including assignees, status, and due dates, with ease. Plus, the Table view lets you quickly check on the progress of each project task.

But that’s not all—you can copy and paste your table into other software, pin specific columns, auto-size your columns, and even share your tables through a unique link.

This simple interface makes it a breeze to drag and drop rows and columns to quickly change your view.

drag and drop tasks on a clickup table

Drag and drop tasks on a ClickUp Table View for simple organization

ClickUp is an all-in-one management software for time tracking and figuring time estimates while supporting dates and times fields, so you can finally break up with Excel for your project management needs.

Don’t believe us? Create your own table for free in ClickUp today!

The past few weeks I have had endless questions about time calculations in Excel. So this week I thought I would share a few with you.

First let’s quickly understand how Excel stores dates and time.

Date and Time 101

Excel stores dates and time as serial numbers. When you format the serial number as a date or time, or date and time as in the example below, it displays it in a date/time format but underlying is still a serial number.

The serial number is made up of two parts.

Serial Number

The digits before the decimal are the date and the digits after the decimal are the time.

Excel Time Serial Numbers

Dates in Excel

Dates in Excel start on 1st January 1900. Therefore the serial number for 1/1/1900 is 1.

The serial number for 1/1/2012 is 40909 because it is the forty thousand, nine hundred and ninth day since 31/12/1899*.

Excel Date Serial Numbers

Note: in Australia our dates are displayed as dd/mm/yyyy.

*Actually 1/1/2012 is only the 40908 day but Excel includes the date 29th Feb 1900 even though 1900 was not a leap year. This inclusion was intentional to provide compatibility with Lotus 1-2-3 which contained the bug and had the market share when Excel was released!

Time serial numbers represent a fraction of a 24 hour day.

Excel Convert Time to decimal

Convert Time to Decimals

Often we need to convert time to a decimal so that we can calculate hours x rate for the purpose of payroll or billing.

It’s easy. Remember, the serial number is a fraction of a day so you simply multiply it by 24.

Excel Convert Time to decimal

Note: you don’t need to enter a date and time. If you enter time only, the date part of the serial number is 0.

OK, now you know the rules let’s look at some examples or working with time.

Shift Work Timesheets and Overtime

Calculating the difference between two times on the same date is as simple as subtracting the start time from the finish time, but it’s not so easy if your start and finish times are on different dates, as in the case of shift workers.

Notice the finish time below for Monday is actually 7AM on Tuesday.

Excel Calculate Overtime

We can use a clever trick to test for time that finishes on a different date by checking whether the finish time is less than the start time, as is the case for Monday and Tuesday above.

Taking the formula in cell G4:

Excel Calculate Overtime

The first part of the formula takes the finish time less the start time and then checks whether the finish time is less than the start time (E4<B4). In the case of Monday (E4<B4) evaluates to TRUE, and since TRUE = 1 it adds 1 to E4-B4 to correctly calculate the time.

Note: if your times are entered with the date and time you can simply subtract one from the other, it’s only in the case where times are entered on their own that you need to test whether the finish time is < the start time.

Rounding Time

I’ve had a few people ask me how to round time in 10 minute increments for the purpose of billing clients at an hourly rate.

The table below shows rounding using the ROUNDUP, MROUND and ROUND functions.

Excel Rounding Time

If you want to bill in 30 minute increments change the 10 in the above formulas to 30.

Display Time with Text

I had a question this week asking how to display time in a format that reads ‘2 hours 15 minutes’.

There are quite a few formulas that will concatenate text for the words ‘hours’ and ‘minutes’, but I prefer to simply use a custom number format.

Excel format time with words

You can see in cell K2 the formula subtracts the start time from the arrival time to give the number of hours late.

I then formatted the cell to show the time with words using a custom number format like this:

Excel custom time format

The benefit of this approach is that the underlying time value remains in the cell so you can use it in other formulas. For example you might like to add up the Time Late column to get a total time late etc.

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

For more time and date related tutorials:

Calculating Time in Excel

TIME Function

EOMONTH Function

EDATE Function

DATEDIF Function

Skip to content

Как посчитать время – разницу, сумму, добавить или вычесть

В статье рассматривается, как в Excel посчитать время. Вы найдете несколько полезных формул чтобы посчитать сумму времени, разницу во времени или сколько времени прошло и многое другое.

Ранее мы внимательно рассмотрели особенности формата времени Excel и возможности основных функций времени. Сегодня мы углубимся в вычисления времени в Excel, и вы узнаете еще несколько формул для эффективного управления временем в ваших таблицах.

Как посчитать разницу во времени в Excel (прошедшее время)

Для начала давайте посмотрим, как можно быстро посчитать в Excel сколько прошло времени, т.е. найти разницу между временем начала и временем окончания. И, как это часто бывает, существует несколько способов для расчета времени. Какую из них выбрать, зависит от вашего набора данных и того, какого именно результата вы пытаетесь достичь. Итак, давайте посмотрим несколько вариантов.

Вычесть одно время из другого

Как вы, наверное, знаете, время в Excel — это обычные десятичные числа, отформатированные так, чтобы они выглядели как время. И поскольку это числа, вы можете складывать и вычитать время так же, как и любые другие числовые значения.

Самая простая и очевидная формула Excel чтобы посчитать время от одного момента до другого:

Время окончания — Время начала

В зависимости от ваших данных, формула разницы во времени может принимать различные формы, например:

Формула Пояснение
=A2-B2 Вычисляет разницу между временами в ячейках A2 и B2.
=ВРЕМЗНАЧ(«21:30») — ВРЕМЗНАЧ («8:40») Вычисляет разницу между указанными моментами времени, которые записаны как текст.
=ВРЕМЯ(ЧАС(A2); МИНУТЫ(A2); СЕКУНДЫ(A2)) — ВРЕМЯ (ЧАС (B2); МИНУТЫ (B2); СЕКУНДЫ (B2)) Вычисляет разницу во времени между значениями в ячейках A2 и B2, игнорируя разницу в датах, когда ячейки содержат значения даты и времени.

Помня, что во внутренней системе Excel время представлено дробной частью десятичного числа, вы, скорее всего, получите результаты, подобные этому скриншоту:

В зависимости оп применяемого форматирования, в столбце D вы можете увидеть десятичные дроби (если установлен формат Общий). Чтобы сделать результаты более информативными, вы можете настроить отображаемый формат времени с помощью одного из следующих шаблонов:

Формат Объяснение
ч Прошедшее время отображается только в часах, например: 4.
ч:мм Прошедшие часы и минуты отображаются в формате 4:50.
ч:мм:сс Прошедшие часы, минуты и секунды отображаются в формате 4:50:15.

Чтобы применить пользовательский формат времени, используйте комбинацию клавиш Ctrl + 1, чтобы открыть диалоговое окно «Формат ячеек», выберите «Пользовательский»  и введите шаблон формата в поле «Тип». Подробные инструкции вы можете найти в статье Создание пользовательского формата времени в Excel .

А теперь давайте разберем это на простых примерах. Если время начала находится в столбце B, а время окончания — в столбце A, вы можете использовать эту простую формулу:

=$A2-$B2

Прошедшее время отображается по-разному в зависимости от использованного формата времени, как видно на этом скриншоте:

Примечание. Если время отображается в виде решеток (#####), то либо ячейка с формулой недостаточно широка, чтобы вместить полученный результат, либо итогом ваших расчетов времени является отрицательное число. Отрицательное время в Экселе недопустимо, но это ограничение можно обойти, о чем мы поговорим далее.

Вычисление разницы во времени с помощью функции ТЕКСТ

Еще один простой метод расчета продолжительности между двумя временами в Excel — применение функции ТЕКСТ:

  • Рассчитать часы между двумя временами:   =ТЕКСТ(A2-B2; «ч»)
  • Рассчитать часы и минуты:                             =ТЕКСТ(A2-B2;»ч:мм»)
  • Посчитать часыминуты и секунды:              =ТЕКСТ(A2-B2;»ч:мм:сс»)

Как видно на скриншоте ниже, вы сразу получаете время в нужном вам формате. Специально устанавливать пользовательский формат ячейки не нужно.

Примечание:

  • Значение, возвращаемое функцией ТЕКСТ, всегда является текстом. Обратите внимание на выравнивание по левому краю содержимого столбцов C:E на скриншоте выше. В некоторых случаях это может быть существенным ограничением, поскольку вы не сможете использовать полученное «текстовое время» в других вычислениях.
  • Если результатом является отрицательное число, ТЕКСТ возвращает ошибку #ЗНАЧ!.

Как сосчитать часы, минуты или секунды

Чтобы получить разницу во времени только в какой-то одной единице времени (только в часах, минутах или секундах), вы можете выполнить следующие вычисления.

Как рассчитать количество часов.

Чтобы представить разницу в часах между двумя моментами времени в виде десятичного числа, используйте следующую формулу:

=( Время окончания — Время начала ) * 24

Если начальное время записано в A2, а время окончания – в B2, вы можете использовать простое выражение B2-A2, чтобы вычислить разницу между ними, а затем умножить результат на 24. Это даст количество часов:

=(B2-A2)* 24

Чтобы получить количество полных часов, используйте функцию ЦЕЛОЕ, чтобы округлить результат до ближайшего целого числа:

=ЦЕЛОЕ((B2-A2) * 24)

Пример расчета разницы во времени только в одной единице измерения вы видите на скриншоте ниже.

Считаем сколько минут в интервале времени.

Чтобы вычислить количество минут между двумя метками времени, умножьте разницу между ними на 1440, что соответствует количеству минут в одном дне (24 часа * 60 минут = 1440).

=( Время окончания — Время начала ) * 1440

Как показано на скриншоте выше, формула может возвращать как положительные, так и отрицательные значения. Отрицательные возникают, когда время окончания меньше времени начала, как в строке 5:

=(B2-A2)*1440

Как сосчитать количество секунд.

Чтобы посчитать разницу в секундах между двумя моментами времени, вы умножаете разницу во времени на 86400, что соответствует числу секунд в одном дне (24 часа * 60 минут * 60 секунд = 86400).

=( Время окончания — Время начала ) * 86400

В нашем примере расчет выглядит следующим образом:

=(B2-A2)* 86400

Примечание. Чтобы результаты отображались правильно, к ячейкам с вашей формулой разницы во времени следует применить общий либо числовой формат.

Как посчитать разницу в каждой единице времени.

Чтобы найти разность между двумя точками времени и выразить ее только в одной определенной единице времени, игнорируя остальные, используйте одну из следующих функций.

  • Разница в часах без учета минут и секунд:

=ЧАС(B2-A2)

  • Разница в минутах без учета часов и секунд:

=МИНУТЫ(B2-A2)

  • Разница в секундах без учета часов и минут:

=СЕКУНДЫ(B2-A2)

При использовании функций Excel ЧАС, МИНУТЫ и СЕКУНДЫ помните, что результат не может превышать 24 для часов, и 60 – для минут и секунд.

В данном случае не играет роли, сколько дней прошло с даты начала до даты окончания. Учитывается только дробная часть числа, то есть время.

Примечание. Однако,если в ячейку вы записали не просто время, а дату и время, и при этом дата окончания окажется меньше даты начала (т. е. результатом будет отрицательное число), то вы увидите ошибку #ЧИСЛО!.

Как перевести секунды в часы, минуты и секунды

Часто случается, что длительность какого-то события представлена в каких-то одних единицах времени. К примеру, различные приборы зачастую возвращают измеренное ими время в секундах. И это число нам нужно перевести в привычный формат времени – в часы, минуты и секунды, а при необходимости – еще и в дни.

Давайте рассмотрим небольшой пример.

Предположим, зафиксирована продолжительность события 284752 секунд. Переведем число секунд в дни, часы, минуты и секунды.

Вот как это будет:

Дни:

=ЦЕЛОЕ(A2/(60*60*24))

Часы:

=ЦЕЛОЕ(A2/(60*60)) — ЦЕЛОЕ(A2/(60*60*24))*24

Минуты:

=ЦЕЛОЕ(A2/60) — ЦЕЛОЕ(A2/(60*60))*60

Секунды – это просто две последние цифры:

=—ПРАВСИМВ(A2;2)

Если нужно рассчитать время только в часах, минутах и секундах, то изменим формулу подсчета часов:

=ЦЕЛОЕ(A2/(60*60))

Конечно, здесь результат может быть больше 24.

Минуты и секунды подсчитываем, как и прежде.

Еще один вариант перевода секунд в дни, часы, минуты и секунды вы можете посмотреть на скриншоте ниже.

Расчет времени с момента начала до настоящего момента

Чтобы рассчитать, сколько времени прошло с какой-то даты до настоящего момента, вы просто используете функцию ТДАТА, чтобы вернуть сегодняшнюю дату и текущее время, а затем вычесть из них  дату и время начала.

Предположим, что начальная дата и время находятся в A2, выражение =ТДАТА()-A2 возвращает следующие результаты, при условии, что вы применили соответствующий формат времени к столбцу B (в этом примере «ч:мм») :

Если прошло больше чем 24 часа, используйте один из этих форматов времени , например Д «дн.» ч:мм:сс, как показано на скриншоте ниже:

Если ваши начальные данные содержат только время без дат, вам нужно использовать функцию ВРЕМЯ, чтобы правильно рассчитать, сколько времени прошло. Например, следующая формула возвращает время, истекшее с момента, указанного в ячейке A2, и до текущего момента:

=ВРЕМЯ(ЧАС(ТДАТА()); МИНУТЫ(ТДАТА()); СЕКУНДЫ(ТДАТА())) — A2

Примечание. Прошедшее время не обновляется в режиме реального времени, оно заново рассчитывается только при повторном открытии или пересчете рабочей книги. Чтобы принудительно обновить результат, нажмите либо Shift + F9, чтобы пересчитать активную таблицу, или F9 для пересчета всех открытых книг. Еще один способ быстрого пересчета – внесите изменения в любую ячейку вашего рабочего листа.

Отображение разницы во времени как «XX дней, XX часов, XX минут и XX секунд».

Это, вероятно, самая удобная формула для расчета разницы во времени в Excel. Вы используете функции ЧАС, МИНУТЫ и СЕКУНДЫ для возврата соответствующих единиц времени, и функцию ЦЕЛОЕ для вычисления разницы в днях. Затем вы объединяете все эти функции в одно выражение вместе с текстовыми пояснениями:

=ЦЕЛОЕ(B2-A2)&» дн., «&ЧАС(B2-A2)&» час., «&МИНУТЫ(B2-A2)&» мин. и «&СЕКУНДЫ(B2-A2)&» сек.»

Вот как это может выглядеть:

Чтобы скрыть нулевые результаты в формуле разницы во времени в Excel, встройте в нее четыре функции ЕСЛИ:

=ЕСЛИ(ЦЕЛОЕ(B2-A2)>0; ЦЕЛОЕ(B2-A2) & » дн.,  «;»») &

ЕСЛИ(ЧАС(B2-A2)>0; ЧАС(B2-A2) & » час.,  «;»») &

ЕСЛИ(МИНУТЫ(B2-A2)>0; МИНУТЫ(B2-A2) & » мин. и  «;»») &

ЕСЛИ(СЕКУНДЫ(B2-A2)>0; СЕКУНДЫ(B2-A2) & » сек.»;»»)

Синтаксис может показаться чрезмерно сложным, но это работает :)

Кроме того, вы можете рассчитать разницу во времени, просто вычитая время начала из времени окончания (например =B2-A2 ), а затем применив к ячейке следующий формат времени:

Д «дн.,» ч «час.,» м «мин. и » с «сек.»

Преимущество этого подхода заключается в том, что вашим результатом будет обычное значение времени, которое вы можете задействовать в других расчетах, в то время как результатом сложной формулы, описанной выше, является текст. 

Недостатком же здесь является то, что пользовательский формат времени не может различать нулевые и ненулевые значения и игнорировать нули.

Как рассчитать и отобразить отрицательное время в Excel

При расчете разницы во времени в Excel вы иногда можете получить результат в виде ошибки ######, если вдруг она представляет собой отрицательное число. Это происходит, если время начала больше, чем время окончания события. Такое часто случается, если рассчитывают продолжительность каких-то событий без учета даты. Получается, что время окончания меньше, чем время начала, поскольку это просто время следующего дня. К примеру, мы начинаем работу в 17 часов и заканчиваем на следующий день в 10 часов.

Но есть ли способ правильно отображать отрицательное время в Excel? Конечно, способ есть, и даже не один.

Способ 1. Измените систему дат Excel на систему дат 1904 года.

Самый быстрый и простой способ нормально отображать отрицательное время (со знаком минус) — это перейти на систему дат 1904 года. Для этого нажмите « Файл» > «Параметры» > «Дополнительно », прокрутите вниз до раздела « При расчете этой книги» и поставьте галочку в поле «Использовать систему дат 1904».

Нажмите OK , чтобы сохранить новые настройки, и теперь отрицательные величины времени будут отображаться правильно, как отрицательные числа:

Как видите, время начала больше, чем время окончания, и результат получен со знаком «минус».

Способ 2. Рассчитать отрицательное время в Excel с помощью формул

Если изменить систему дат по умолчанию в Excel нецелесообразно, вы можете заставить отрицательное время отображаться правильно, используя одну из следующих формул:

=ЕСЛИ(A2-B2>0; A2-B2; «-» & ТЕКСТ(ABS(A2-B2);»ч:мм»))

=ЕСЛИ(A2-B2>0; A2-B2; ТЕКСТ(ABS(A2-B2);»-ч:мм»))

Они обе проверяют, является ли отрицательной разница во времени (A2-B2). Если она меньше нуля, первая формула вычисляет абсолютное значение (без учёта знака) и объединяет этот результат со знаком «минус». Вторая формула делает точно такой же расчет, но использует отрицательный формат времени «-ч::мм «.

Примечание. Имейте в виду, что в отличие от первого метода, который обрабатывает отрицательное время как отрицательное число, результатом функции ТЕКСТ всегда является текстовая строка, которую нельзя использовать в математических вычислениях.

Если же текстовый формат для вас нежелателен, то вы можете определить разницу во времени в абсолютном выражении, игнорируя знаки.

На случай если время окончания меньше, чем время начала, мы можем проверить это при помощи функции ЕСЛИ.

=ЕСЛИ(B2<A2;B2+1;B2)-A2

Если разница во времени отрицательная, ко времени окончания добавляем 1 день (24 часа).  В результате получим правильную разницу во времени, но без знака «минус».

Сложение и вычитание времени в Excel

По сути, есть 2 способа сложения и вычитания времени в Excel:

  • При помощи функции ВРЕМЯ.
  • Применяя арифметические вычисления, основанные на количестве часов (24), минут (1440) и секунд (86400) в одних сутках.

Функция ВРЕМЯ(часы; минуты; секунды) делает вычисления времени в Excel очень простыми, однако не позволяет добавлять или вычитать более 23 часов, 59 минут или 59 секунд. 

Если вы работаете с большими временными интервалами, то используйте один из способов, описанных ниже.

Как добавить или вычесть часы

Чтобы добавить часы к заданному времени в Excel, вы можете взять на вооружение одну из следующих формул.

Функция ВРЕМЯ для добавления до 24 часов

Время начала + ВРЕМЯ( N часов ; 0 ; 0)

Например, если ваше время начала записано в ячейке A2, и вы хотите добавить к нему 2 часа, формула выглядит следующим образом:

=A2 + ВРЕМЯ(4; 0; 0)

Примечание. Если вы попытаетесь добавить более 23 часов с помощью функции ВРЕМЯ, указанные часы будут разделены на 24, а остаток от деления будет добавлен к времени начала. Например, если вы попытаетесь добавить 28 часов к «10:00» (ячейка A2) с помощью формулы =A4 + ВРЕМЯ(28; 0; 0), результатом будет «14:00», т. е. A2 + 4 часа.

Как добавить любое количество часов (меньше или больше 24 часов)

Следующая формула не имеет ограничений на количество часов, которые вы хотите добавить:

Время начала + ( N часов / 24)

Например, чтобы добавить 36 часов к времени начала в ячейке A2:

=A2 + (36/24)

Чтобы вычесть часы из заданного времени, вы используете аналогичные формулы и просто заменяете «+» знаком «-»:

Например, чтобы вычесть 40 часов из времени в ячейке A2, можно употребить формулу:

=A2-(40/24)

Если вычитаем менее чем 24 часа, то используйте функцию ВРЕМЯ:

=A2 — ВРЕМЯ(4; 0; 0)

Как прибавить или вычесть минуты

Чтобы добавить минуты к заданному времени, используйте те же методы, которые мы только что использовали для добавления часов.

Чтобы добавить или вычесть менее 60 минут

Используйте функцию ВРЕМЯ и укажите минуты, которые вы хотите добавить или вычесть, во втором аргументе:

Время начала + ВРЕМЯ(0; N минут ; 0)

Вот несколько примеров для расчета минут в Excel:

Чтобы добавить 30 минут ко времени в A2:  =A2 + ВРЕМЯ(0;30;0)

Чтобы вычесть 50 минут из времени в A2:     =A2 — ВРЕМЯ(0;50;0)

Как добавить или вычесть более 60 минут

При расчете разделите количество минут на 1440, то есть на количество минут в сутках, и прибавьте получившееся число к времени начала:

Время начала + ( N минут / 1440)

Чтобы вычесть минуты из времени, просто замените плюс знаком минус. Например:

Чтобы добавить 600 минут:     =A2 + (600/1440)

Чтобы вычесть 600 минут:        =A2 — (600/1440)

Как прибавить или вычесть секунды

Подсчеты с секундами в Excel выполняются аналогичным образом как с минутами. Ограничение здесь, как вы понимаете, 60 секунд.

Чтобы добавить менее 60 секунд к заданному времени, вы можете использовать функцию ВРЕМЯ:

Время начала + ВРЕМЯ(0; 0; N секунд )

Чтобы добавить более 59 секунд, используйте следующую формулу:

Время начала + ( N секунд / 86400)

86400 – это количество секунд в сутках.

Чтобы вычесть секунды, используйте те же формулы, только со знаком минус (-) вместо плюса (+).

Это может выглядеть примерно так:

Чтобы добавить 50 секунд к A2:         =A2 + ВРЕМЯ(0;0;50)

Чтобы добавить 1500 секунд к A2:      =A2 + (1500/86400)

Чтобы вычесть 25 секунд из A2:          =A2 — ВРЕМЯ(0;0;25)

Чтобы вычесть 2500 секунд из A2:      =A2 — (2500/86400)

Примечание:

  • Если вычисленное время отображается в виде десятичного числа, примените настраиваемый формат даты/времени к ячейкам.
  • Если после применения пользовательского форматирования в ячейке отображается #########, то скорее всего, ячейка недостаточно широка для отображения даты и времени. Чтобы исправить это, увеличьте ширину столбца, дважды щелкнув или перетащив правую его границу.

Как суммировать время в Excel

Формула суммирования времени в Excel — это обычная функция СУММ, и применение правильного формата времени к результату — это то, что помогает получить верный результат.

Предположим, у вас есть сведения об отработанном времени в столбце B, и вы хотите его суммировать, чтобы посчитать общее количество рабочих часов за неделю. Вы пишете простую формулу СУММ 

=СУММ(B2:B8)

 Затем устанавливаете в ячейке нужный формат времении получаете результат, как на скриншоте ниже.

В некоторых случаях формат времени по умолчанию работает просто отлично, но иногда вам может понадобиться более тонкая настройка шаблона, например, для отображения общего времени в виде минут и секунд или только секунд. Хорошей новостью является то, что никаких других вычислений не требуется. Все, что вам нужно сделать, это применить правильный формат времени к ячейке.

Щелкните правой кнопкой мыши ячейку и выберите «Формат ячеек» в контекстном меню или нажмите Ctrl + 1, чтобы открыть диалоговое окно «Формат ячеек». Выберите «Пользовательский» и введите один из следующих форматов времени в поле «Тип»:

  • Чтобы отобразить общее время в часах и ​​минутах: [ч]:мм
  • Чтобы отобразить общее время в минутах и ​​секундах: [м]:сс
  • Чтобы отобразить общее время в секундах: [сс]

Примечание. Вышеупомянутые пользовательские форматы времени работают только для положительных значений. Если результатом ваших расчетов времени является отрицательное число, например, когда вы вычитаете большее время из меньшего, результат будет отображаться как #####. Чтобы по-другому отображать отрицательное время, см. раздел Пользовательский формат для отрицательных значений времени .

Кроме того, имейте в виду, что формат времени, примененный к ячейке, изменяет только представление на дисплее, не изменяя содержимое ячейки.  На самом деле это обычное время, которое хранится в виде десятичной дроби во внутренней системе Excel. Это означает, что вы можете свободно ссылаться на него в других формулах и вычислениях.

Вот как вы можете рассчитывать время в Excel. Чтобы узнать о других способах управления датами и временем в Excel, я рекомендую вам ознакомиться с ресурсами в конце этой статьи. Я благодарю вас за чтение и надеюсь увидеть вас в нашем блоге. 

Как перевести время в число В статье рассмотрены различные способы преобразования времени в десятичное число в Excel. Вы найдете множество формул для преобразования времени в часы, минуты или секунды. Поскольку Microsoft Excel использует числовую систему для работы с временем, вы можете…
Формат времени в Excel Вы узнаете об особенностях формата времени Excel, как записать его в часах, минутах или секундах, как перевести в число или текст, а также о том, как добавить время с помощью…
Как вывести месяц из даты На примерах мы покажем, как получить месяц из даты в таблицах Excel, преобразовать число в его название и наоборот, а также многое другое. Думаю, вы уже знаете, что дата в…
Как быстро вставить сегодняшнюю дату в Excel? Это руководство показывает различные способы ввода дат в Excel. Узнайте, как вставить сегодняшнюю дату и время в виде статической метки времени или динамических значений, как автоматически заполнять столбец или строку…
Количество рабочих дней между двумя датами в Excel Довольно распространенная задача: определить количество рабочих дней в период между двумя датами – это частный случай расчета числа дней, который мы уже рассматривали ранее. Тем не менее, в Excel для…

Skip to content

All Excel’s Date Functions Explained + Time Functions Too! [+5500 words]

All Excel’s Date and
Time Functions Explained!

Written by co-founder Kasper Langmann, Microsoft Office Specialist.

This is the complete guide to date and time in Excel.

It’s a whopping +5500 words (!), so be sure to bookmark it.

The first part of the guide shows you exactly how to deal with dates in Excel.

I will show you how to perform calculations involving dates. We’re also going to look at some of Excel’s (awesome) built-in functions. These allow you to extract just what you need from data that includes dates.

In the second part of the guide, I’ll show you how to work with time data in a spreadsheet.

This is going to be a lot of fun. Grab a cup of coffee, and let’s start rolling!

Kasper Langmann, Co-founder of Spreadsheeto
  • 7: Date formatting

    • What is date formatting?
    • How to use other date formats (from the ‘Format Cells’ dialog box)
    • How to use custom date format
    • Turn text into dates with the DATEVALUE function
    • How to auto populate date in Excel when a cell is updated
    • How to insert a date picker in Excel

Get your FREE exercise file

Before you start:

Throughout this guide, you need a data set to practice.

I’ve included one for you (for free).

Download it right below!

Introduction to
calculations with dates

When analyzing and manipulating date information in Excel, you have several formatting options.

In other words, you can display your data in many ways.

Most of the time, Excel will know that you are entering a date when you key in the data like the following:

  • 1/1/2017
  • January 1, 2017
  • 1-Jan

The clearest sign that Excel has stored your data in a cell as a date is that it should be right-aligned in the cell.

Kasper Langmann, Co-founder of Spreadsheeto

Below are a few examples of the various formats that Excel displays dates in.

But the key is that they are all aligned to the right of the cell.

Data formatted as data versus text

Contrast column A with column B (where the cells are formatted as text). They show the same information.

But, the alignment to the left side of the cell indicates that they are not formatted as a date. As you will soon see, this presents problems when performing calculations with dates.

Kasper Langmann, Co-founder of Spreadsheeto

One important note about how Excel stores dates:

To use dates in calculations, Microsoft Excel stores dates as serial numbers.

These are the sequential number of the day in relation to the starting date of January 1, 1900.

Short data format and serial number

So, think of January 1, 1900, as serial number 1.

January 1, 2016, would be serial number 42370 as it’s 42,370 days after January 1, 1900.

For this reason, dates need to be in a date format rather than text format. If stored in text format, their serial number will not be stored in Excel. This is a no-go as you need these serial numbers when you want to perform calculations involving dates.

Kasper Langmann, Co-founder of Spreadsheeto

How to add time to dates in Excel

Now you know the fundamentals of date formatting versus date data formatted as text. Let’s look at some calculations you can do with dates.

First, why don’t we look at how to add days to a date?

Kasper Langmann, Co-founder of Spreadsheeto

How to add days to a date

Adding days to a date is very simple, straightforward, and intuitive.

All you need to do is add the number of days as a single number to the date or cell reference containing the date.

The following figure illustrates just how simple it is to add 1 day or 90 days to a date.

Example of adding days

How to add months to a date

If you need to add a month or several months to your date, the process is a bit more complicated.

For this calculation, you will need to call upon the built-in Excel function, EDATE. The syntax for EDATE is so simple, that you will pick it up in no time at all.

Kasper Langmann, Co-founder of Spreadsheeto

Here’s its syntax:

=EDATE(start_date, months)

The function requires 2 arguments: ‘start_date’ and ‘months’.

The first, ‘start_date’, is simply the date we are adding months to.

The second, ‘months’, is the number of months we would like to add to the date.

Look at the figure below to see just how easy it is to calculate a new date by adding 6 months and 9 months to the start date.

Adding months to a date

How to add years to a date

So, what about calculating the addition of years to your original date?

For this, you need to use a few more functions. But, as noted before, this is super intuitive so don’t let the length of these formulas fool you.

Kasper Langmann, Co-founder of Spreadsheeto

The first function we need to focus on is DATE.

The syntax for DATE is also incredibly simple and intuitive:

=DATE(year, month, day)

But, for our purposes, we can use the YEAR, MONTH, and DAY functions along with DATE.

These functions extract the correct data from our original date. This ensures appropriate use of our final DATE formula.

For example, applying MONTH to a cell reference of our original date will extract the month data. The same is true for YEAR and DAY.

So, we will place these functions in the appropriate argument within the DATE function. And if we want to add 1 year to the date, we simply place a ‘+1’ after the YEAR function in the ‘year’ argument of the DATE function.

Kasper Langmann, Co-founder of Spreadsheeto

That was a lot, so let’s look at the following figure to see it in action.

The function DATE in action

Notice row 18 and column C of the worksheet.

The ‘year’ argument of the ‘DATE’ function is substituted by the function ‘YEAR(A18)+1’.

This tells the DATE function that we want the year only from the date data in A18 (or 2017) – and that we want to add ‘1’ to it (or 2018).

How to subtract dates

Adding time to a date is super useful.

But what if you had a report where you needed to calculate the difference between dates?

This is where we turn our attention to subtracting dates…

Kasper Langmann, Co-founder of Spreadsheeto

Find the difference between two dates

To find the difference between two dates, we want to turn our attention to the DATEDIF function.

The most important thing you need to know about DATEDIF is that it is a hidden function. What that means is that it will not be found in the visible list of Excel functions on the formula tab.

Kasper Langmann, Co-founder of Spreadsheeto

This requires you to type the formula in its entirety.

There will be no tooltip hint as you begin to type the function.

Let’s look at the syntax:

=DATEDIF(start_date, end_date, unit)

There are three arguments for the DATEDIF function:

  • start_date: This is the initial date of the period among the two you are calculating the difference between.
  • end_date: This is the latest date of the two.
  • unit: This is the unit in which you want the function to return the difference by. More on units right below…

The ‘unit’ argument gives you a choice of several formats to return your results from DATEDIF.

  • y – The number of complete years between dates.
  • m – The number of complete months between dates.
  • d – The number of days between dates.
  • md – The number of days ignoring months and years.
  • yd – The number of days ignoring years.
  • ym – The number of months ignoring days and years.

So, let’s look at a few examples using DATEDIF in various forms.

Kasper Langmann, Co-founder of Spreadsheeto
Function DATEDIF

In our example, you can use literal dates if they are enclosed in double quotes.

You can also use the serial number format as shown in rows 4 and 5.

Now note the difference in the returned value between row 2 and 3. The ‘start_date’ and the ‘end_date’ are unchanged. But, our results are different. The first formula returns the total number of days between the dates.

Kasper Langmann, Co-founder of Spreadsheeto

But in the second example, we use ‘md’ for the unit argument. ‘md’ is the difference between the dates in days – ignoring the months and years. That is 15 minus 1, or 14 days.

You can also calculate the difference between two dates in cells.

To do this, place the cell reference of your dates in the ‘start_date’ and ‘end_date’ arguments.

Difference between two dates in cells

One (last) important thing to note about using DATEDIF:

The ‘end_date’ argument must always be later than the ‘start_date’ or you will get the ‘#NUM!’ error.

Use today’s date in Excel

Now let’s turn our attention to some tricks and shortcuts involving the current date.

Often, you need to work with the current (today’s) date.

There are some nifty tricks that allow you to do this without typing in the entire date manually.

Let’s look at them!

Use date that updates itself with the TODAY function

One of the simplest ways to input today’s date into a cell is to use the TODAY function.

Do this by typing ‘=TODAY()’ into a cell.

This places the current date into the cell dynamically. So, that cell would have tomorrow’s date in it if you reopen the file tomorrow.

You can also nest the TODAY function within the DAY or MONTH function. This return only the current day or current month in a cell. Refer to the following figure to see the TODAY function in action.

Kasper Langmann, Co-founder of Spreadsheeto
TODAY function

Insert static current date in Excel using shortcuts

You can also insert the current date using keyboard shortcuts.

For the current date, press the following key combination:

Ctrl + ;

To insert both the date and the time, press the previous keyboard shortcut. Then press the following combination:

Ctrl + Shift + ;

These shortcuts enter static dates and times. This opposed to the dynamic date that the TODAY function returns.

Subtract a date from the current date

You can use the current date in a calculation like subtracting.

You replace the ‘start_date’ argument in the DATEDIF formula.

Subtract a date with DATEDIF

Above image shows how to substitute the TODAY function for a literal date value or cell reference for the ‘start_date’ OR the ‘end_date’.

Remember the rule that the ‘end_date’ must be later than the ‘start_date’ still applies.

Using the TODAY function in a calculation is useful when you need to track a time period dynamically. Say you need to calculate some sort of countdown to a deadline. Using the TODAY function in your calculation is the perfect way to do this.

Kasper Langmann, Co-founder of Spreadsheeto

You can also use the keyboard shortcut to insert the current date if you need to insert the static date. This is a quicker and more efficient way to insert today’s date.

Retrieving numbers from dates
with Date functions

There are often situations where you need to retrieve numbers from dates.

But, you might not have the need for an entire date.

Let’s say you have a report. Here you want to separate the different elements of the date for filtering by a single element of the date – like the month or year.

Here’s how to go about doing that 🙂

Use the DAY function to find the day of a date

To isolate only the day of the full date, we use the DAY function.

There is a single argument for the DAY function:

=DAY(serial_number)

You probably know by now that ‘serial_number’ is the date.

This argument can be the actual serial number form of the date or the literal date in double quotes. It can also be a cell reference like in the following example.

DAY function

Look at above picture again. Notice that regardless of the format of your original date, the DAY function returns the value ‘14’.

Use the MONTH function to find the month of a date

If you need to isolate the number value for the month of your original date, you can use the MONTH function.

It works the same way the DAY function works:

=MONTH(serial_num)

MONTH function

Use the YEAR function to find the year of a date

Now we move onto the function that retrieves the number value for the year part of the date.

The syntax for the ‘YEAR’ function is like the DAY and MONTH functions syntactically.

=YEAR(serial_num)

You already know how to retrieve the day and month number values. It’s the exact same concept when using the ‘YEAR’ function.

YEAR function

Use the WEEKDAY function to find the day of the week

You can also retrieve the number value for the day of the week from a date.

The WEEKDAY function returns the number that corresponds to the day of the week. For instance, 1 for Sunday, 2 for Monday, 3 for Tuesday, and so on.

Kasper Langmann, Co-founder of Spreadsheeto

Here’s its syntax:

=WEEKDAY(serial_num, [return_type])

The syntax for WEEKDAY requires the ‘serial_number’ argument.

It also allows for an optional argument: ‘return_type’.

This allows you to choose a different start and end date for your week.

That means that the returned value will align with that chosen sequence.

Below you can see the list of different ‘return_type’ values that Excel allows.

WEEKDAY function

In the following examples, note the value differences returned by the formula based on the ‘return_type’ argument.

Value differences returned by formula based on ‘return_type’ argument

The different selections for the ‘return_type’ in the formulas return very different weekday values.

These depend on the first day of the week that corresponds to those ‘return_type’ values.

Use the WEEKNUM function
to find out the week number

Another interesting built-in function is the WEEKNUM function.

WEEKNUM retrieves the number value for the week of the year that the original date falls within (1 – 52).

So, if the original date is between January 1 and January 7, the WEEKNUM value would be ‘1’.

If the date is between December 25 and December 31, WEEKNUM would return the value ‘52’.

=WEEKNUM(serial_number, [return_type])

The ‘return_type’ argument corresponds to different days you can choose as the start day. This changes the week number based on what day of the week that the ‘return_type’ sets as the first day of the year.

Kasper Langmann, Co-founder of Spreadsheeto
WEEKNUM function

Our date falls on a Monday.

The result of the WEEKNUM formula will be different if the ‘return_type’ argument is ‘1’ (Sunday) versus ‘12’ (Tuesday).

This can be useful since the calendar year begins on different days of the week. This comes in handy if want to calculate the week number based on the first full week of the year.

Kasper Langmann, Co-founder of Spreadsheeto
WEEKNUM example

This can be a very useful function.

Consider a situation in which you needed a weekly countdown. Simply calculate the difference between dates using the WEEKNUM function.

Use the WORKDAY function to calculate the number of working days between two dates

Another useful function is the WORKDAY function.

This function returns a day that is some number of workdays into the future or before some date. A “workday” is days excluding weekends and any holidays that are specified.

The function requires two arguments and has an optional third.

=WORKDAY(start_date, days, [holidays])

  • start_date this required argument is the date from when you want to count the number of workdays
  • days this required argument is the number of days from the start date you want a count of. Using a negative number will give you the date that many workdays before your start date.
  • holidays this argument is optional. This allows you to add holiday dates in the formula for the WORKDAY function to skip along with weekends.

This is a bit more complex than the functions we have been discussing. Let’s look at a few examples to help the concept of the WORKDAY function sink in.

Kasper Langmann, Co-founder of Spreadsheeto
Function WORKDAY

First, note that we have listed 3 holiday dates in cells A8, A9, and A10. We will be using these in our examples for the ‘holiday’ argument to exclude along with weekends.

On row 2, we want to know the date that is 90 workdays from Monday, November 14, 2016.

Excluding the weekends and holidays (A8:A10), this will be Tuesday, March 21, 2017 according to the WORKDAY function.

On row 3, we can instantly see the effect of weekends and holidays on the outcome of our formula. We want the date that is 2 workdays from Wednesday, November 23, 2017.

Because of the holiday on Thursday, November 24 – and the weekend days Saturday and Sunday – the result is Monday, November 28, 2016.

This example illustrates how powerful the WORKDAY function can be. It calculates something very simple. Yet, if done manually, this is a very cumbersome process.

Kasper Langmann, Co-founder of Spreadsheeto

The third example in the figure illustrates how to use WORKDAY to find a date before the start date.

We want to know the date that is 20 workdays before Monday, January 17, 2017.

So, our DAY argument needs to be a negative value (-20).

Again, note the result considers weekend days as well as a couple of holidays.

How to auto fill dates

In this section, we are going to cover how to work with sequences of dates. This time by using the autofill capability of Microsoft Excel.

You can use Autofill in 2 ways.

The first is to double-click the fill handle. The fill handle is a small square that appears in the lower right corner of a highlighted cell.

The second option is to simply drag the handle to the desired cell. Note the fill handle for the highlighted cell in the following figure.

Auto fill handle

The fill handle also offers some more options.

Try to right-click and drag outside the selection a bit.

Auto fill menu

We will focus on the selections that fill elements of the date like days, weekdays, months, and years.

Insert dates that increase by one day

To insert dates that increase by one day in a column, you can simply grab the fill handle.

Then drag it down as many rows as you need dates for.

One thing to take note of is that as you do this, Excel shows the incremented date as you drag the range.

So, you can see just what date you are at as you expand the range.

Expand range

Once you release the fill handle, your range is now filled with dates.

These dates increment in one-day intervals.

Range expanded

Insert dates that increase by weekdays

But what if you wanted to increment a wide range of dates by weekdays only?

This is easily done by selecting ‘Fill Weekdays’ from the ‘Autofill Options’ that appears once you fill the dates down.

Fill weekdays

Once you select ‘Fill Weekdays’, Excel automatically excludes any weekend dates from the range.

Weekdays added

Insert dates that increase by months and years

You can also use the ‘Autofill Options’ to increase months and years.

Select the fill option you need once you fill the dates down to the last cell of your range.

Autofill examples

Insert dates that increase by several days

I’m sure you can think of other custom intervals (dates) you might like to fill down your column (or row, for that matter).

Microsoft Excel allows for a little of that also.

So, what if you wanted to increment every other day? Or what about every 3 months?

These other intervals are available using auto fill. Drag down the dates by using the fill handle. Then right click and hold on the fill handle while moving the cursor slightly outside the range. Now release until you see the options menu.

Kasper Langmann, Co-founder of Spreadsheeto
Series

Click on ‘Series…’. The Series dialog box will now open.

This gives you several options for customizing the intervals of your dates.

Series dialog box

For our example of every other day, you can select a Step value of ‘2’.

Leave everything else as it is.

Every other day

Date formatting:
Make a date easy to interpret

In the beginning of this tutorial, I told you about the differences between text format and date format.

Now, we’re going to take a deeper dive into formatting of dates. We can represent date data in different date formats. These are easily adjusted according to our preferences and needs.

Kasper Langmann, Co-founder of Spreadsheeto

Also, remember our point earlier, that Excel stores date data as serial number.

So, no matter what date format you choose, Excel still recognizes it as a serial number.

What is date formatting?

Date formatting offers you choices on how you want to represent the date data in your worksheets.

Let’s look at our original example at the beginning of this tutorial.

We can see in the Number group of the Home tab that our data cells are all formatted as Date.

Date formatting

If you take the same data and place it into another column, something interesting happens.

In the cells that are formatted as ‘General’, you’d see the dates serial numbers.

Formatted as date and general

If you run into this in your own spreadsheets, you must know how to fix this…

It’s quite simple, you just need to know how to reformat those cells into the Date format that you need.

For this example, let’s reformat to ‘Short date’.

Highlight the cell containing the serial number. Click on the drop-down arrow to see all the available formats in the Number group of the Home tab.

Short date

Select ‘Short Date’ from the dropdown and now the serial number will be converted from ‘General’ format to a date format that you recognize.

Short date applied

How to use other date formats
from the ‘Format Cells’ dialog box

You’ve now seen how to change date data formatted as ‘General’ to the ‘Short Date’ format.

Now we look at some other date formats that Excel also offers…

You already know how to change to a date format from the ribbon but you can also use the ‘Format Cells’ dialog box.

The first step is to find the cell that contains the serial number you want to reformat.

Then, right-click on the cell.

Select ‘Format Cells’ from the menu that appears.

Format cells dialog box

From the Format Cells dialog box, select ‘Date’ in the Category box.

This reveals the different standard date format types available in Excel.

You find these formats in the Type box on the right side of the Format Cells dialog box. As you change Type selections, you can view a sample of the actual value in the cell you have selected in the Sample box.

Kasper Langmann, Co-founder of Spreadsheeto
Format cells as date

Decide on the ‘Type’ you want.

Then click ‘OK’ and the serial number now changes to the date format type you selected.

Converted date

How to use custom date format

Even with all the date types Excel offers, you can still format your date data with your own custom format.

It is pretty simple to do…

Follow the same steps as we did with the previous example.

But, instead of choosing ‘Date’ in the Category box in the Format Cells dialog box, select ‘Custom’.

Format cells as custom

Take a second look at the picture above.

Here the Format Cells dialog box shows the current format of the cell in the Type and Sample boxes.

Now you can select from the various default types available. You can also edit those types in the Type box or type in one that is completely custom.

Kasper Langmann, Co-founder of Spreadsheeto

Let’s clear out the Type box…

Clear type box

And then type “mm-dd-yyyy”  into that box:

mm-dd-yyyy

Again, note that as we do this, the Sample box shows us our exact data as it will look under our new custom format. Click ‘OK’ and you are done creating your own custom date format.

Kasper Langmann, Co-founder of Spreadsheeto

Turn text into dates with the DATEVALUE function

Another method for converting dates in text format is to use a function called DATEVALUE.

This function converts text string dates to their appropriate serial numbers.

These serial numbers are, as you know by now, the way Excel recognizes dates. You can format this output according to the methods I’ve shown you in the prior sections.

Kasper Langmann, Co-founder of Spreadsheeto

The DATEVALUE syntax is simple:

=DATEVALUE(date_text)

So, let’s look at a few examples of cells containing dates that are in text string form.

Let’s use the DATEVALUE function in the column next to these cells.

Here it’s easy to see if the cells return the serial numbers we expect.

DATEVALUE

If your text date is before the year 1900, the DATEVALUE function will return the ‘#VALUE!’ error.

That’s because Excel recognizes dates as serial numbers beginning at January 1, 1900.

If your text date doesn’t contain a year, the DATEVALUE function defaults to the current year from your system clock.

How to auto populate date when a cell is updated

What if you wanted to make sure each time a cell’s data got updated, you knew when it was updated?

You could input the date and time manually in the cell next to it.

But what if you wanted to automate that process?

That way you’ll never forget to do it. Also, you would mitigate the chances for a data entry error.

There are several ways to approach this. One of the best ways is to use VBA to create a worksheet change event. It is a macro that automatically runs when a cell’s value changes.

Kasper Langmann, Co-founder of Spreadsheeto

A quick recommendation:

Excelribbon.tips.net has written an awesome guide that demonstrates a worksheet change event. Make sure to check it out!

How to insert a date picker in Excel

Another cool thing you can do in Excel with dates is to create a date picker. This allows users to choose a date from a preset dropdown calendar. That way they don’t have to input the date by hand.

This is actually a pretty complex proposition in Excel. But if you want to see a date picker and a bit about how one can be created using VBA. Contextures has an amazing guide to do it right here.

Calculations with Time

Maybe you need to quantify elapsed time for tasks or projects?

Or perhaps you need to insert a time rather than a date in your data?

There are many parallels between the techniques of working with dates and time.

How to add time in Excel

Let’s look at a scenario where you have documented the total time it took for two different tasks in Excel.

Now you want to add those together to get your total time worked.

This is as simple as clicking on the cell below the task times and pressing Alt + = to autosum the times.

SUM time

Now let’s look at a scenario where you have the times worked for a full workweek that you need to add together for a total.

If we autosum once again, we immediately notice a problem.

AUTOSUM time problem

We know by simple inspection that these workday time values add up to more than 12 hours and 52 minutes.

Excel can display times in a variety of ways. For instance, hours and minutes, 12-hour format, and 24-hour format, and several others.

Kasper Langmann, Co-founder of Spreadsheeto

What we need to do in our current situation is to right click on the cell where our auto sum formula is.

Then select Format Cells like we did with dates.

hours minutes minutes

Then select ‘Custom’ from the Category box and clear the Type box.

Then in the Type box, type ”[h]:mm”.

Click ‘OK’ and you should have the correct total of hours for the week now.

Time correct displayed

How to find the difference between two times

Finding the difference between times is not quite as simple as adding times together.

Let’s look at a situation where we have a start time and an end time and we want to calculate the total elapsed time.

Finding time difference

In cell B4, type the formula ‘=(B3-B2)*24’.

This subtracts the end time from the start time and then multiplies both by 24.

The multiplication by 24 is required since Excel recognizes times as a fraction of a full 24-hour day.

Formula =(B3-B2)*24

Our result is a numerical value and we choose to set it to two decimal places to show fractions of a full hour.

Numerical time difference

If you want to see the elapsed time in the actual hours and minutes, here’s what to do.

Remove the ‘*24’ and format using the custom format we created in the previous example adding times ([h]:mm).

Find current time in Excel

The NOW function allows you to insert the current time based on your computer’s system clock.

NOW returns the current date and time whereas TODAY returns the current date only.

But we can use NOW and format our cell so that it only shows the time but not the date.

NOW function

Insert static current time with shortcuts

You’ve already seen the keyboard shortcut for entering in the static current date as well as entering the static current time.

Since we are discussing time data, I’ll show you how to use a keyboard shortcut to enter the static current time.

All you must do is press the following keyboard combination:

Ctrl + Shift + ;

Again, this contrasts with using the NOW function because it is static rather than dynamic.

This keyboard shortcut inserts the exact time you pressed the keyboard shortcut. It will remain that time unless you manually change it.

Retrieve seconds, minutes and hours

Let’s look at retrieving parts of time data.

This is very much the same as when you retrieved the month, day, and year, from dates. We are going to retrieve the seconds, minutes, and hours with some built-in functions available in Excel.

If you want to retrieve the seconds from a time value in Excel, you use the built-in SECOND function.

There is a single required argument for this function: ‘serial_number’.

=SECOND(serial_number)

Let’s look at a few simple examples to see this function in action:

SECOND function

For times that don’t display the seconds, the SECOND function still retrieves the seconds from the serial number of the date.

If you need to retrieve the minutes from your time data, you want to use the MINUTE function. Like with SECOND function (and others), there is only the required ‘serial_number’ argument.

=MINUTE(serial_num)

Now we will take the same time data we used for the SECOND function and use the MINUTE function.

MINUTE function

The last thing we will look at is the HOUR function. Nothing new on the syntax.

=HOUR(serial_number)

One thing to note about the HOUR function is that it returns a value for the hour based on 24 hours.

So, if you want your HOUR function to return the hour in an AM/PM fashion, subtract 12 from your function if it is a time later than 12 PM.

HOUR function

Formatting time: What is it?

Just like with dates, there are several different format types for time data.

In fact, our examples so far have demonstrated a few of these different formats.

You may want to display times in 12-hour format or 24 hours. You might want your 12-hour format times to show AM and PM, or you may not.

Kasper Langmann, Co-founder of Spreadsheeto
Default time

You find the default time format types by right-clicking a cell.

Then select Format Cells.

Note in the figure above how many variations you can choose from. You can always create your own custom format by selecting ‘Custom’ from the Category list.

How to use and change time formatting

Now we have reviewed how you select different time formats.

Let’s look at a few examples of the different types.

We will look at 3 different selections from those available in the types for time formats.

The first thing we need to do to change format is to right click on the range of dates we want to reformat. Then select Format Cells.

Format cells

Once the Format Cells dialog opens, select ‘Time’ from the Category box. Then in the Type box select ‘*1:30:55 PM’.

Format cells as time

The asterisk in ‘*1:30:55 PM’ indicates that this format changes to the Region settings on your computer.

Any changes to the Windows time format settings will reflect in Excel. But only for the times formatted with a format preceded by an asterisk.

So, we format column B times as ‘*1:30:55 PM’ and then two other formats in columns C and D for the sake of contrast. Look at the different format variations in the following figure.

Kasper Langmann, Co-founder of Spreadsheeto
Examples of different times

Turn text into time with the TIMEVALUE function

The DATEVALUE function converts dates in text string form to date formatting.

Like DATEVALUE, the TIMEVALUE function converts text string time data to actual time format.

See the syntax here:

=TIMEVALUE(text_time)

The ‘text_time’ argument is required. It is simply the text string date that you need to convert to time format.

One thing to recall is that Excel recognizes time as a fraction of 24 hours. For instance, 12 pm would be interpreted by Excel as .5 since it is the halfway point of the 24-hour day.

Kasper Langmann, Co-founder of Spreadsheeto

So, when you use the TIMEVALUE function, you won’t get a time.

Rather, it returns a decimal number value that is a fraction of the entire day.

TIMEVALUE function

If you multiply the TIMEVALUE result by 24, you get a more accurate interpretation of the time (albeit still in decimal format).

TIMEVALUE in 24 hours

But if you reformat the TIMEVALUE result to a time format, you are good to go.

You will have changed a text string time to a true time format that Excel will now recognize as time instead of text.

Wrapping up

There it is, the most comprehensive guide to date and time in Excel.

It’s taken us tons of hours and resources to publish. Feel free to share it along with anyone who needs to brush up their dates and times 😊

If you enjoyed this tutorial, I’m sure you’ll love this…

Kasper Langmann2020-05-11T13:30:38+00:00

Page load link

As the name suggests, the timesheet is a method used in recording time. In the timesheet method, we enter a person’s time in and time out to calculate the total time spent on the job. Originally, it was developed for an employer to calculate payroll considering the lunch or the break time taken by the person.

Table of contents
  • Excel Timesheet Calculator
    • How to Create Timesheet Calculator in Excel? (with Examples)
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

How to Create Timesheet Calculator in Excel? (with Examples)

The timesheet uses the following inputs from the user:

You can download this Time Sheet Excel Template here – Time Sheet Excel Template

  1. In time
  2. Out Time
  3. Break-In Time
  4. Break Out time

The user can manually enter these inputs to calculate the total time spent.

We subtract the “In Time” from “Break in Time” and “Out Time” from “Break out Time” to exclude the break time taken by the employee.

You can download this Time Sheet Excel Template here – Time Sheet Excel Template

Example #1

The timesheet calculator in Excel records the time a person worked on a job. In the first example, we will learn about the basic timesheet and move to a professional one.

The format of the Excel timesheet looks like this:

Time sheet in Excel example 1

The user will manually enter the values in date, time in, time out, lunch in, and lunch out. And apply the Excel timesheet calculation with formulas in which it will calculate total working hours.

Below are the steps for creating a timesheet calculator in Excel:

  1. First, in cell F1, write an Excel equation.

    Time sheet in Excel example 1-1

    The total working hours are calculated by the total time spent by a person while deducting the lunchtime taken by the person.

  2. Drag the formula to Cell F6 as we will make 5 entries.

    Time sheet in Excel example 1-2

  3. Now, input the date and the rest of the values.

    Time sheet in Excel example 1-3

    Our first timesheet calculates the total hours a person spends on a job.

Example #2

Let us professionally make a timesheet.

For a company to calculate the time worked by its employees and the overtime time that has been done, it needs to calculate the payrollPayroll refers to the overall compensation payable by any organization to its employees on a certain date for a specific period of services they have provided in the entity. This total net pay comprises salary, wages, bonus, commission, deduction, perquisites, and other benefits.read more.

The standard working hours for the company are 8 hours. For the mandatory 8 hours, the pay is ₹500, while for overtime, the pay is ₹650.

The format is as below:

TimeSheet in Excel example 2

  • Step 1 – First, let us input the standard working hours in cell K2.

TimeSheet in Excel example 1

We have used the TIME excel functionTime is a time worksheet function in Excel that is used to calculate time based on the inputs provided by the user. The arguments can take the following formats: hours, minutes, and seconds.read more so that the hours are 8 hours, 0 minutes, and 0 seconds. Anything above that will be considered overtime.

  • Step 2 – In Excel, getting the format correct is the key. Let us insert the formula in the F2 cell to calculate the total time worked by an employee.

TimeSheet in Excel example 2

  • Step 3 – We want our cell to be in the correct format, so right-click on the cell and go to the “Format Cells” and select the “General” category from the “Number” section.

TimeSheet in Excel example 3

  • Step 4 – Go to “Custom” and select “h:mm” for hours and minutes.

TimeSheet in Excel example 4

  • Step 5 – Drag it to cell F6.

TimeSheet in Excel example 5

  • Step 6 – In the “Regular” column, the regular hours are eight hours a day but let us say if the total number of working hours exceeds eight hours a day. Then, it should display the total working hours, if not the regular eight hours.

For this, we can use an IF function. In cell G2, write the Excel timesheet formula:

TimeSheet in Excel example 6

We have locked cell K1 as it will not change as a reference.

  • Step 7 – Drag cell G2 to G6.

TimeSheet in Excel example 7

  • Step 8 – Cell G2 is showing an incorrect value because of incorrect formatting.

So now, to get the correct value, we need to click on cell G2. Press right-click, then go to the “Format Cells” section, and in “Custom,” select “h:mm” and click “OK.”

TimeSheet in Excel example 8

  • Step 9 – Use an excel format painterFormat painter in Excel is a tool used to copy the same format of a single cell or a group of cells to the other cells. You will find it on the home tab in the clipboard section.read more brush to copy the same format for the cells below.

example 9

  • Step 10 – Now, let us calculate overtime hours worked by an employee. In cell H2, write the Excel timesheet formula:

example 10

It will calculate the overtime done by an employee.

  • Step 11 – Drag this to cell H6.

example 11

  • Step 12 – Always remember to check the correct format. Right-click on the selected cells, and go to the “Format Cells” section. In “Custom,” select h:mm then click “OK” and get the correct value.

example 12

  • Step 13 – Calculate the working hours by summing the cells F2 to F6.

example 13

  • Step 14 – The data is in time format. To change it to number format to calculate the pay, in cell F9, write the below formula.

example 14

  • Step 15 – Repeat the same for overtime hours,

example 15

  • Step 16 – Now, change the format for cellsFormatting cells is an important technique to master because it makes any data presentable, crisp, and in the user’s preferred format. The formatting of the cell depends upon the nature of the data present.read more F9 and H9 to number format by right-clicking. Then, in the “Format Cells, click on the “Number.”

example 16

  • Step 17 – For regular working hours, the pay is ₹500, and for overtime hours, the payment is ₹650. First, calculate the pay by the below formula.

example 17

  • Step 18 – Now, start giving the inputs to see the result.

example 18

The total pay received by the employee will be ₹22287.5. 

Things to Remember

  1. Formatting is the key in the timesheet calculator in Excel.
  2. We must always use h:mm, i.e., hours and minutes format, to calculate time.

Recommended Articles

This article has been a guide to Timesheets in Excel. Here, we discuss creating a timesheet calculator in Excel using formulas and examples and downloadable Excel templates. You may also look at these useful functions in Excel: –

  • Create Excel Time Card TemplateManagers and owners can use an excel time card template to keep track of their employees’ and workers’ attendance, leaves, and efficiency.read more
  • VBA TimeValueVBA’s Time Value function is part of the date and time category, and it returns the numerical value of the date provided in as an argument.read more
  • Time Tracking TemplateA time tracking template helps keep the organization track of the hours dedicated by its employees during a designated period.read more
  • Timeline Chart in ExcelIn project management terms, an Excel timeline chart is also known as a Milestone chart. It is used to visually track all stages of a project and assists a project manager in delivering the project to the end-user as committed before the start of the project.read more

If you use Excel regularly, I’m sure you’ve come across dates and times in your cells. Data often has a record of when it was created or updated, so knowing how to work with this data is essential.

Here are three key skills that you’ll learn in this tutorial:

  • How to format dates in Excel so that they appear in your preferred style
  • Formulas to calculate the number of days, months, and years between two dates
  • An Excel date formula to log today’s date, and a keyboard shortcut to add the current time

Microsoft Excel can basically do anything with data, if you just know how. This tutorial is another key step to adding skills to your Excel toolbelt. Let’s get started.

Excel Date and Time Formulas (Quick Video Tutorial)

This screencast will walk you through how to work with dates and times in Excel. I cover formatting dates to different styles, as well as Excel date formulas to calculate and work with dates. Make sure to download the free Excel workbook with exercises that I’ve attached to this tutorial.

Keep reading for a written reference guide on how to format dates and times in Excel, and work with them in your formulas. I’ll even share several tips that weren’t covered in the screencast.

Typing Dates and Times in Excel

For this part of the tutorial, use the tab titled «Typing Dates & Times» in the example workbook.

One of the keys to working with dates and times in Excel is capturing the data correctly. Here’s how to type dates and times in your Excel spreadsheets: 

1. How to Type Dates

I recommend typing dates in the same format that your system uses. For our American readers, a full date would be in the «day/month/year» format. European style dates are «month/day/year.»

Date in ExcelDate in ExcelDate in Excel

When I’m typing dates, I always type in the full date with the month, day and year. If I only want to show the month and the year, I’ll simply format it that way (more on that in a minute.)

2. How to Type Times

It’s easy to type times in Excel. We can specify anything from just an hour of the day, to the exact second that something took place.

If I wanted to log the time as 4PM, I’d type «4 pm» into a cell in Excel and then press enter:

Excel timesExcel timesExcel times

Notice once we press enter, Excel converts what we’ve typed into a hours : minutes: seconds data format. 

Here’s how to log a more specific time in your spreadsheet:

More specific time format in ExcelMore specific time format in ExcelMore specific time format in Excel

The key is to use colons to separate the section of the time data, and then add a space plus «AM» or «PM.»

3. How to Type Date-Time Together

You can also type combinations of dates and times in Excel for highly specific timestamps.

To type a date-time combination, simply use what we’ve already learned about typing dates, and typing times. 

Combined date and time formats in ExcelCombined date and time formats in ExcelCombined date and time formats in Excel

Notice that Excel has converted the time to a 24 hour format when it’s used in conjunction with a date, by default. If you want to change the style of this date, keep reading.

Bonus: Excel Keyboard Shortcut for Current Time

One of my favorite Excel keyboard shortcuts inserts the current time into a spreadsheet. I use this formula often, when I’m noting the time I made a change to my data. Try it out:

Control + Shift + ;

Formatting Dates in Excel

For this part of the tutorial, use the tab titled «Formatting Dates & Times» in the example workbook.

What can you do when your dates are European style dates? That is, they’re in a day-month-year format, and you need to convert them to the more familiar month-day-year format?

Excel Multiple Date-Time Formats

All of these cells contain exactly the same data, they’re just formatted in different ways.

In the screenshot above, what might surprise you is that all six of those cells contain exactly the same data — «1/22/2017.» What differs is how they’re formatted in Excel. The original data is identical, but it can be formatted to show in a variety of ways.

In most cases, it’s better to use formatting to modify the style of our dates. We don’t need to modify the data itself — just change how it’s presented.

Format Excel Cells

To change the appearance of our date and time data, make sure that you’re working on the Home tab of Excel. On the Ribbon (menu at the top of Excel), find the section labeled Number. 

There’s a small arrow in the lower right corner of the section. Click it to open the Format Cells menu.

Excel Format CellsExcel Format CellsExcel Format Cells

To format cells in Excel with built in styles, make sure you’re working on the Home tab and click the dropdown arrow next to the word «Number» in this screenshot.

The Format Cells menu has a variety of options for styling your dates and times. You could turn «1/22/2017» into «Sunday, January 22nd» with just formatting. Then, you could grab the format painter and change all of your cell styles.

Format Cells ExcelFormat Cells ExcelFormat Cells Excel

The Format Cells menu allows you to change the styles of your dates and times without the work of changing the original date.

Spend some time exploring this menu and trying out the different styles for your Excel dates and times.

Get Data From Dates and Times

Let’s say that we have a list of data that has very specific dates and times, and we want to get simpler versions of those formulas. Maybe we have a list of exact transaction dates, but we want to work with them at a higher level, grouping them by year or month.

You can get the year from a date with this Excel formula:

=YEAR(CELL)

Year MonthYear MonthYear Month

To get just the month from a date cell, use the following Excel formula:

=MON(CELL)

Month FormulaMonth FormulaMonth Formula

Find the Difference Between Dates and Times

For this part of the tutorial, use the tab titled «DATEDIF» in the example workbook.

While formats are used to change how dates and times are presented, formulas in Excel are used to modify, calculate, or work with dates and times programatically.

The DATEDIF formula is powerful for calculating differences between days. Give the formula two dates and and it will return the number of days, months, and years between two dates. Let’s look at how to use it.

1. Days Between Dates

This Excel date formula will calculate the number of days between two dates:

=DATEDIF(A1,B1,"d")

The formula takes two cells, separated by commas, and then uses a «d» to calculate the difference in days. 

DATEDIF daysDATEDIF daysDATEDIF days

The DATEDIF formula takes two date cells and calculates the days between them.

Here are some ideas for how you could use this Excel date formula to your advantage:

  • Calculate the difference between today and your birthday to start a birthday countdown
  • Use a DATEDIF to calculate the difference between two dates and divide your stock portfolio’s growth by the number of days to calculate the growth (or loss!) per day

2. Months Between Dates

DATEDIF also calculates the number of months between two dates. This date formula in Excel is very similar, but substitutes an «m» for «d» to calculate the difference in months:

=DATEDIF(A1,B1,"m")

However, there’s a quirk in the way Excel applies DATEDIF: it calculates whole months between dates. See the screenshot below.

Datedif MonthsDatedif MonthsDatedif Months

To me, there are three months between January 1st and March 31st (all of January, all of February, and almost all of March.) However, because Excel uses whole months, it only considers January and February as completed, whole months, so the result is «2.» 

Here’s my preferred way to calculate the number of months between two dates. We’ll find the date difference in days, and then divide it by the average number of days in a month — 30.42 . 

=(DATEDIF(A1,B1,"d")/30.42)

Let’s apply our modified DATEDIF to two dates:

Much better. The output of 2.99 is very close to 3 full months, and this will be much more useful in future formulas.

The official Excel documentation has a complex method to calculate months between dates, but this is a simple and easy way to get it pretty close. Writing a good Excel formula is about finding the sweet spot of precision and simplicity, and this formula does both.

3. Years Between Dates

Finally, let’s calculate the number of years between two dates. The official way to calculate years between dates is with the following formula:

=DATEDIF(A1,B1,"y")

Notice that this is the same as our past DATEDIF formulas, but we’ve simply substituted the last part of the formula with «y» to calculate the number of years between two dates. Let’s see it in action:

Excel formula for calculating years between datesExcel formula for calculating years between datesExcel formula for calculating years between dates

Notice that this works like the DATEDIF for months: it counts only full years that have passed. I’d rather include partial years passing as well. Here’s a better DATEDIF for years:

=(DATEDIF(A1,B2,"d")/365)

Basically, we’re just getting the date difference in days, and then dividing it by 365 to calculate it as a year. Here’s the results:

Better Excel formula for calculating years between datesBetter Excel formula for calculating years between datesBetter Excel formula for calculating years between dates

DATEDIF is extremely powerful, but watch out for how it works: it’s going to only calculate full months or years that have passed by default. Use my modified versions for more precision in the results.

Bonus: Work Days Between Dates

The Excel date formulas covered above focus on the number of business days between dates. However, it’s sometimes helpful to just calculate the number of workdays (basically weekdays) between two dates.

In this case, we’ll use =NETWORKDAYS to calculate the number of workdays between two dates.

=NETWORKDAYS(A1,B1)

In the screenshot below, I show an example of using NETWORKDAYS. You can see the calendar showing how the formula calculated a result of «4.» 

Using Excel Date Formula with NETWORKDAYSUsing Excel Date Formula with NETWORKDAYSUsing Excel Date Formula with NETWORKDAYS

If you have known holidays in the timeframe that you want to exclude, check out the official NETWORKDAYS documentation.

Recap and Keep Learning

Dates and times are ubiquitous to spreadsheets. Excel date formulas and formatting options are helpful. The techniques in this tutorial can take your Excel skills to the next level so that you can incorporate date-driven data seamlessly into your spreadsheets.

You’ve added one skill to your Excel toolbox — why stop here? Chain Excel formulas and skills to create powerful spreadsheets. To keep learning more about working with Excel spreadsheets, check out these other resources:

  • IF Statements are logic built into your spreadsheet that show results based on conditions. You could combine an IF Statement with a date range to show data based on a date or time. Check out this tutorial to learn them.
  • You could combine the VLOOKUP tutorial with date and time formulas to match values based on a date or time.
  • Find and Remove Duplicates is an Excel function used in combination with date and time data, as it’s often one of the best bits of data to check for duplicates.

How do you work with calendar and time data in your Excel spreadsheets? Are there are any Excel date or time formulas that I’m missing from this tutorial that you use regularly? If so, let me know in the comments.

Понравилась статья? Поделить с друзьями:
  • Calculation table in excel
  • Calculation in excel column
  • Can cut and paste in word
  • Calculating worksheets in excel
  • Can csv files open in excel