Search code examples
excelworksheet-function

Excel date/time difference


I would like to work out the current time since a date and time specified.

If the specified data is : 19/01/2013 16:44:00
and now the time is : 19/01/2013 16:45:00

the difference is 0 years 0 months 0 days 0 hours 1 minute 0 seconds

This can be done easily just by taking the current time and minus the previous time and format it but this is hard to crunch data so what I wish to do is break each date/time segment into its own cell

Let's say cell A1 has the previous time and cell A2 has the current time

Cells a5 trough f5 would contain 0 years 0 months 0 days 0 hours 1 minute 0 seconds

On a second note on this question is it possible to force the =NOW() to update every x seconds via VBA without interaction?


Solution

  • You can't use YEAR function to get year difference because that will give 1 year between 31st December 2012 and 1st Jan 2013 when there is only one day.....

    ....similarly you can have problems with MONTH and DAY (e.g. MONTH always returns a number between 1 and 12 whereas in this context you would only expect numbers between 0 and 11)

    Try DATEDIF for the first 3 then HOUR, MINUTE, SECOND as Justin suggests

    Assuming start date/time in A2 and end date/time in B2 try these formulas respectively for Years, Months, Days, Hours, Minutes and Seconds

    =DATEDIF(A2,B2-(MOD(A2,1)>MOD(B2,1)),"y")

    =DATEDIF(A2,B2-(MOD(A2,1)>MOD(B2,1)),"ym")

    =DATEDIF(A2,B2-(MOD(A2,1)>MOD(B2,1)),"md")

    =HOUR(B2-A2)

    =MINUTE(B2-A2)

    =SECOND(B2-A2)

    format all cells as general

    You may get some discrepancies because of variable month/year lengths......