Date Time (Maati)
Date Time (Maati)
BY :NOORAIN ANSARI
Suggest you make changes such as the following so that all of your dates will display as four
digit years. If you do not do this you may not be able to distinguish which part of the date is the
year, the month, day; and have further difficulty knowing whether you actually have a 19xx year
or a 20xx year. Excel will keep track of dates but it may not be what you see displayed or you
may not be sure.
The short date format in Regional settings is used by Excel for the General format.
The long date format in Regional settings is used by Excel for the Headings and Footings under
page setup.
Differences in Regional Settings may not be immediate apparent. Time in the US like
=TEXT(A1,"[hh]:mm") might be =TEXT(A1,"[TT}:mm") in another language, incorrect use
results in a #VALUE! error. Within double quotes such formulas may not translate in an
exchange of workbooks (??).
When Excel has recognized through some means that you have a date -- entered as a date or
assigned by a formula based on a cell that had a date, the short date form from your Windows
Regional Settings will be used if your cell format is General. You can override the default
formatting by specifically formatting a the column, for instance, with the date format of your
choice.
Created by www.excelvbaclinic.com
Page 1
DATE & TIME
To format hours so that they don’t roll over into days format as [h]:mm or as [hh]:mm
An interesting format was pointed out by Dave Peterson where mm/dd/yyyy* dddd, places the
date left justified (US format) and the day spelled out and right justified within the cell as
||11/14/2001 Wednesday||. It is typical number formatting but interesting applied to dates.
Ctrl+Shift+# Apply the Date format with the day, month, and year
Ctrl+Shift+@ Apply the Time format with the hour and minute, and indicate A.M. or P.M.
The use of NOW() will place the system date and time into the cell The format is dependent on
your date and time settings (International settings).
TIME in VBA only goes down to hh:mm, to get hh:mm:ss you need to use NOW. Excel does
not provide a finer time accuracy. There are some examples of using Time in Event macros
upon change of another cell or by double-click on a cell. If you need to time events to 10ms
Created by www.excelvbaclinic.com
Page 2
DATE & TIME
(hundreth of a second) using a timer started when you boot up see Simple Timer used for
checking timing on code.
†
See "Number format codes for dates and times" in help.
example of time format: hh:mm:ss
examples of date or custom date format: mm/dd/yyyy and dddd mmmm dd, yyyy
Excel trickery: if you enter the formula =NOW() into a cell and then hit F9 (calculate) without
hitting Enter, it will convert the unentered formula to a constant without formatting of it's own,
so you should format the column.
--> For more information about number format codes for dates and times, click [>>]
Entering a month and day, or a month and year will cause the formatting to change for a General
Cell. This can also produce problems if the figure entered is actually a fraction and not a date.
(partial solution)
Created by www.excelvbaclinic.com
Page 3
DATE & TIME
In XL95 the windowing for 2 digit dates (date window) is 00-19 represents 2000-2019, and 20-
99 represents 1920-1999. The windowing dates change with later versions of Excel. XL97 and
XL98(Mac) use 00-29 and 30-99.
Programming: end of current month: (NOW is a datetime serial and has both components)
ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0)
ActiveCell.NumberFormat = "DDD MM/DD/YYYY"
You would actually format the entire column for best usage, without formatting in code.
Created by www.excelvbaclinic.com
Page 4
DATE & TIME
To assign a variable
Dim MyDate as Date
ActiveCell.Value = DateSerial(Year(Now), Month(Now) + 1, 0)
While col A may have started out as format General, Excel and VBA will change the formatting
from General. VBA time and now in VBA will truncate seconds, so you see 06.98 secons from
Excel NOW() and 07.00 from the Excel TIME, and 06.00 seconds from VBA. Due to the
truncation of seconds, VBA is not going to match your system clock. VBA Excel now() will
include fractional seconds. If you want something for timing fractional seconds see Simple
Timer on my “Slow Response” page used to time code to thousandths of a second. I have yyyy-
mm-dd as my date in Regional Settings and hh:mm for my time (not hh:mm A/P).
Format
Format as
as Formula or constant
hh:mm:ss.0 VBA coding
Genera =personal.xls!GetFormula(An)
0
l
2005-
04-20 09:10:06.00 38462.3820138889 [a2] = Now 'date and time
09:10
2005-
00:00:00.00 38462 [a3] = Int(Now) 'date
04-20
2005-
00:00:00.00 38462 [a4] = Date 'date
04-20
2005-
04-20 09:10:06.00 38462.3820138889 [a5] = Date + Time 'same as now
09:10
Genera 0
l
1900-
01-00 09:10:06.98 =MOD(NOW(),1) [a8] = "=MOD(NOW(),1)"
09:10
=TIME(HOUR(NOW()),MINUT [A9] = "=TIME(HOUR(NOW()),
09:10
09:10:07.00 E( MINUTE(NOW()),SECOND(NOW()
AM
NOW()),SECOND(NOW())) ))"
2005-
[a10] = Now 'date and time
04-20 09:10:06.00 38462.3820138889
(timestamp)
09:10
09:10:0
09:10:06.00 0.382013888888889 [a11] = Time 'time
6 AM
Adding one month to the 31st in a calendar month can present a problem in interpretation. Here
is one solution:
To add one month to a date (i.e. 01/28/2001 through 01/31/2001 becomes 02/28/2001)
x = DateAdd("m", 1, x - 1)
'yyyy Year, q Quarter, m Month, y Day of year, d Day, w Weekday, ww Week, h Hour, n Minute, s Second
Dates and times are both recorded in units of days and the actual number may be referred to as a
dateserial or a timeserial. They can be entered in VBA as dateserial(year,month,day) and with
timeserial(hour,minute,second). As worksheet functions you would use
=DATE(year,month,day) and =TIME(hours,minutes,seconds) You can add the two to get a
datetimeserial.
Time is recorded in days, so 1 hour = 1/24 day = .0417 day (approx); 1 minute = 1/(24*60) =
.000694 days (approx); 1 second = 1/(24*60*60) = .00001157 days (approx)
Assuming that you actually have minutes and seconds multiply by 1440 and format as a number
with 2 digits.
If on the other hand you really entered as hours and minutes multiply by 24 and format as a
number with 2 digits.
A B C
1 display 0:01:15 0.000868055555555556
2 display 1/0/00 12:00 AM =B1
Created by www.excelvbaclinic.com
Page 6
DATE & TIME
Example: Since 2:15 (2 hours 15 minutes = 0.093750 days) is stored as a fractional day you must
multiply by 24 to get 2.25 hours.
Suppose you record units in B1 over time in B2 as in transmitting 8 million bytes in 8 minutes,
you would put 8000000 in B1 and 0:8:00 in B2. Example:
A B C D =GetFormula(cell)
1 Bytes 8,000,000 400,000,000 8000000
2 minutes 0:08:00 0:08:00 0.00555555555555556
3 datetimeserial 0.005555556 0.005555556 =B2
4
5 bytes/day 1,440,000,000 72,000,000,000 =B1/(B2)
6 bytes/hour 60,000,000 3,000,000,000 =B1/(B2*24)
7 bytes/min 1,000,000 50,000,000 =B1/(B2*24*60)
8 bytes/sec 16,666.67 833,333.33 =B1/(B2*24*60*60)
This is just an example and bears no relationship to any actual transmissions times.
The following shows how Excel interprets Data Entry: — Yellow represents time greater than
one hour — A3>=TIME(1,0,0)
A B C D
1 problems with mm:ss.ttt, hh:mm, days & time
2 Default Display General d hh:mm:ss.000
3 12:00.5 12:12:00 AM 0 00:12:00.500 entered as 12:00.5
Created by www.excelvbaclinic.com
Page 7
DATE & TIME
A B C
12/04/195
1 Count of dates within December of any year
2
12/01/199 6
2 =SUMPRODUCT(N(MONTH(A1:A20)=12))
9
11/16/200
3
0
11/30/200
4 Count of dates found within December, 2000
0
12/01/200 4
5 =SUMPRODUCT((MONTH(A1:A20)=12)*(YEAR(A1:A20)=2000))
0
12/05/200
6
0
12/15/200
7 Count of dates found between Nov 16, 2000 and Dec 15, 2000
0
12/31/200 5 =SUMPRODUCT(N(A1:A20>DATE(2000,11,15))*N(A1:A20<=DATE(200
8
0 0,12,15)))
5
9 =countif(A1:A20,">=11/16/2000")-countif(A1:A20,">12/15/2000")
1
0
1 02/05/200 Count of Tuesdays between two dates (i.e. Tue Feb 5, 2002 to Tue Feb 12,
1 2 2002)
1 02/12/200
2 =INT((A12-A11)/7)+IF(WEEKDAY(A11+4)+MOD(A12-A1,7)>=7,1)
2 2
The first two formulas are based on 2000-11-20 George Simms reply in misc and the third
reworked from the first. Cells A9:A20 are BLANK. Note #VALUE! would result if any cell in
range was otherwise not numeric. For more information on SUMPRODUCT see Excel HELP.
The penultimate solution using COUNTIF was posted by Tom Ogilvy 2000-11-21. The last
solution was posted by George Simms 2000-02-19
Created by www.excelvbaclinic.com
Page 8
DATE & TIME
Adding six months to a date may have different interpretations. For instance what is six months
from a date if the month six months later does not have the same number of days. (see Norman
Harker link below)
A B C
08/1 02/1
5/20 5/20 =DATE(YEAR(A1),MONTH(A1)+6,DAY(A1))
1
00 01
08/3 03/0
1/20 3/20 =DATE(YEAR(A2),MONTH(A2)+6,DAY(A2))
2
00 01
3
08/1 02/1
5/20 1/20 =A4 + 180
4
00 01
08/3 02/2
1/20 7/20 =A5 + 180
5
00 01
6
08/1 02/1
5/20 3/20 =A7 + 365/2
7
00 01
08/3 03/0
1/20 1/20 =A8 + 365/2
8
00 01
9
08/1 02/2
1
5/20 8/20 =DATE(YEAR(A10),Month(A10)+7,0)
0
00 01
08/3 02/2
1
1/20 8/20 =DATE(YEAR(A11),Month(A11)+7,0)
1
00 01
1
2
1 08/1 02/1 =IF(DAY(DATE(YEAR(A13),MONTH(A13)+6,DAY(A13)))<>DAY(A13),DAT
3 5/20 5/20 E(YEAR(A13),MONTH(A13)+7,0),DATE(YEAR(A13),MONTH(A13)+6,DAY(
Created by www.excelvbaclinic.com
Page 9
DATE & TIME
00 01 A13)))
1 08/3 02/2 =IF(DAY(DATE(YEAR(A14),MONTH(A14)+6,DAY(A14)))<>DAY(A14),DAT
4 1/20 8/20 E(YEAR(A14),MONTH(A14)+7,0),DATE(YEAR(A14),MONTH(A14)+6,DAY(
00 01 A14)))
A shorter solution than seen in the last two rows adding 6 months is a solution attributed to Chip
Pearson as described in a posting (as a tutorial) by Norman Harker (2002-10-13) in worksheet
functions adding one month, you can add one month to a Jan 31st date for your own test.
=DATE(YEAR(F2),MONTH(F2)+1,MIN(DAY(F2),DAY(DATE(YEAR(F2),MONTH(F2)+2,0
))))
Also See use of DATEDIF on this page, and explanation of DATEDIF Worksheet Function on
one of Chip Pearson's pages. Not to be confused with dissimilar DATEDIFF VBA function.
Time Sheets, providing for start and end time through midnight (#thrumidnight)
The following logical formula tests start time (A1) against end time (B1) and adds 1 if A1 is
greater than B1. If A1>B1 a true condition exists, value 1 (1=24 hours); otherwise, a false
condition exists, value 0
John Walkenbach has sample time sheets on his site see Related areas at end of this web page.
Created by www.excelvbaclinic.com
Page 10
DATE & TIME
Note the use of Format(cell.Value, "Short Date") which will use your Regional Settings to
format the short date.
Sub ConvertFromDateSerial()
'Convert from dateserial to formatted date text constant
'For Excel dateserials on/after March 1, 1900
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim cell As Range
On Error Resume Next '-- in case no cells selected
For Each cell In Intersect(Selection, _
Selection.SpecialCells(xlCellTypeConstants))
cell.Value = Format(cell.Value, "Short Date")
'see help for "Named Date/Time Formats (Format Function)"
Next cell
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Sub ConvertToDateSerial()
'Convert from recognizable US date to date serial
'For dates on/after March 1, 1900 back to dateserial
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim cell As Range
On Error Resume Next '-- in case no cells selected
For Each cell In Intersect(Selection, _
Selection.SpecialCells(xlCellTypeConstants))
cell.Value = Int(DateValue(cell.Value))
cell.NumberFormat = "general"
Next cell
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Created by www.excelvbaclinic.com
Page 11
DATE & TIME
Dates are in cells as mmddyyyy and time are hhmm, need to correct these text entries '01312000
to 01/31/2000 and '0136 to 01:36
=DATE(right(a1,4),left(a1,2),mid(a1,3,2) =TIME(left(b1,2),right(b1,2))
A B C D
1 Name Birthdate Friends Formula
Created by www.excelvbaclinic.com
Page 12
DATE & TIME
2 Bart 03/12/1984 3
The array formula is entered with
3 Bobby 11/02/1985 2
Ctrl-Shift-Enter
4 Chris 02/02/1980 4 do not enter the braces.
5 Leslie 12/25/1975 1
Read more about Array Formulas
6 Pat 08/29/1986 6
on Chip Pearson's site.
7 Toby 02/14/1983 3
8
9 Feb Invite 7 {=SUM((C2:C7)*(MONTH(B2:B7)=2))}
10 Feb Birthdates 2 {=SUM(1*(MONTH(B2:B7)=2))}
Either of these methods will create a date serial from the date not dissimilar from how your
system is setup. The formatting in the resulting cells will display the date format desired. Now
would be a good time to start using four digit dates if you aren’t already.
1. Use Worksheet Function =Datevalue(text) will convert most anything if the date
is in the same format as your system is set up, or
2. Create the dateserial by placing a 1 in a cell on spreadsheet, copy it (Ctrl+C) and
then select the column or whatever of text dates and use Paste Special feature with
Multiply. Better to copy an empty cell, the select the range to convert and use
Edit, PasteSpecial, Add (see Make True Date).
Now what to do if the dates are not in the same format as your system. UK text dates (i.e.
dd/mm/yy) coming in on a US/Canada system (i.e. mm/dd/yy) to be formatted for US/Canada.
You may have to use MID and worksheet function =DATE(year,month,day).
To get a date into text so that it can be left justified and span columns.
=TEXT(NOW(),"mmmm dd, yyyy")
Created by www.excelvbaclinic.com
Page 13
DATE & TIME
1 03/27/1989 3/27/89
2 05/09/1998 =TODAY() same as INT(NOW())
3 9 =DATEDIF(A1,A2,"y") age in years
4 1 =DATEDIF(A1,A2,"YM") plus months
5 12 =DATEDIF(A1,A2,"md") plus days
6 Calculate number of days to next birthday (also see days to upcoming anniversary date)
7 322 =DATE(YEAR(A1)+A3+1,MONTH(A1), DAY(A1))-A2
Column B shows formula used in Column A, =GetFormula(cell)
As long as you have date & time in each cell as entered by Excel you simply subtract the earlier
timestamp from the later timestamp to get a differences in days and/or hours and/or minutes but
since months do not have the same number of days and years don't have the same number of
days, you probably want to use the DATEDIFF Worksheet Function to get differences between
dates as people think of these differences.
Obviously the accuracy in figuring this is hard to determine but comes close to how people often
perceive differences. The accuracy to seconds is not valid (the first timestamp) is simply a date,
but shows how to format hours, minutes and seconds with the TEXT function for formatting as
text.
As you can see February (29 days in leap year) is the base month for the calculation for start date
in February when the day of the month in Feb is greater than the day of the end month of
January. When the start date and end date are both in months with 31 days there is a jump of two
days in the results at that transition point.
B C D
1 Start End Perceived Difference using DATEDIF
2004-02-28 2007-01-13 2 years, 10 months, 15 days, 20 hours, 37 minutes, and
2
15:43:00 12:20:08 08 seconds
2004-02-29 2007-01-13 2 years, 10 months, 14 days, 20 hours, 37 minutes, and
3
15:43:00 12:20:08 08 seconds
2004-03-01 2007-01-13 2 years, 10 months, 11 days, 20 hours, 37 minutes, and
4
15:43:00 12:20:08 08 seconds
2005-03-02 2007-01-13 1 years, 10 months, 10 days, 20 hours, 37 minutes, and
5
15:43:00 12:20:08 08 seconds
2006-01-12 2007-01-12 0 years, 11 months, 30 days, 23 hours, 00 minutes, and
6
23:00:00 22:00:00 00 seconds
2007-01-12 2007-01-13 0 years, 0 months, 0 days, 13 hours, 20 minutes, and
7
23:00:00 12:20:08 08 seconds
2007-01-13 2007-01-13 0 years, 0 months, 0 days, 12 hours, 20 minutes, and
8
00:00:00 12:20:08 08 seconds
Created by www.excelvbaclinic.com
Page 14
DATE & TIME
Microsoft has removed DATEDIF from their knowledge database ( thread). Chip Pearson
maintains DATEDIF information on his site. In XL95 you must use the Analysis Toolpak add-
in. The DATEDIF() worksheet function apparently comes with XL97 and is officially included
in XL2000 and documented in the XL2000 help file (you can see here -- xlfctDATEDIF.htm).
Later versions of Excel dropped DATEDIF from the help file.
KB216578 indicates that DATEDIF is not supported in the Office Worksheet Component
meaning it is not available in interactive HTML created from Excel 2000.
Counting Years, Months and Days similar using VBA DATEDIFF to return a three cell array.
Tip 55 - John Walkenbach - also gives an idea of what an array formula is and how to
implement.
KB149689 XL: Visual Basic Macro Examples for Working With Arrays.
If you have XL97 or later suggest dumping DATEDIF for John Walkenbach’s
XDATEDIF Extended Date Functions Add-In, eliminating problems with negative dates
involving subtraction in MS date system and incorrect leap years in older MS 1900 date system.
(also dates prior to 1900 below).
The following was posted by Chip Pearson on 6Dec1999 and probably can be found on his site.
Function Age(TheDate As Double) As String
Age = _
CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""y"")")) & "
years " & _
CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""ym"")")) & "
months " & _
Created by www.excelvbaclinic.com
Page 15
DATE & TIME
CStr(Evaluate("=DATEDIF(" & TheDate & "," & CDbl(Now) & ",""md"")")) & "
days"
End Function
Harlan Grove posted an interesting formula that does not require DATEDIFF to yield age:
=YEAR(TODAY()-birthdate)-YEAR(0)
=DAY(DATE(my_year,my_month+1,1)-1)
31 =DAY(DATE(1998,7+1,1)-1)
First, Last, Nearest, Closest, nth weekday (4th Monday) in Month, Date
calculations (#firstdate)
WEEKDAY Worksheet Function (1=Sun, 2=Mon, 3=Tues, 4=Wed, 5=Thur, 6=Fri, 7=Saturday)
First Monday of Month (day of month 1-7): 1 + correction
Third Monday of Month (day of month 15-21): 15 + correction
04/14/ Sa
7 36995
2001 t
First Day of 04/08/ Su
1 =B1-WEEKDAY(B1)+1
Week 2001 n
Last Day of 04/14/ Sa
7 =B1-WEEKDAY(B1)+7
Week 2001 t
First Day of 04/01/ Su
1 =DATE(YEAR(B1),MONTH(B1),1)
Month 2001 n
Last Day of 04/30/ M
2 =DATE(YEAR(B1),MONTH(B1)+1,0)
Month 2001 on
First Day of 04/01/ Su
1 =DATE(YEAR(B1),MONTH(B1),1)
Year 2001 n
Last Day of 12/31/ M
2 =DATE(YEAR(B1)+1,1,0)
Year 2001 on
Closest 04/16/ 2M =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY
Monday 2001 on (B1),1,0,-1,-2,-3,3,2,1))
Next Monday 04/16/ 2M =DATE(YEAR(B1),MONTH(B1),DAY(B1)+CHOOSE(WEEKDAY
Created by www.excelvbaclinic.com
Page 16
DATE & TIME
2001 on (B1),1,7,6,5,4,3,2))
Next Monday 04/16/ 2M =A1-WEEKDAY(A1,2)+8
2001 on
1st Monday 04/02/ 2M =DATE(YEAR(B1),MONTH(B1),CHOOSE(WEEKDAY(DATE(YE
of Month 2001 on AR(B1),MONTH(B1),1)),2,1,7,6,5,4,3))
2nd Monday 04/09/ 2M =DATE(YEAR(B1),MONTH(B1),7+CHOOSE(WEEKDAY(DATE(
of Month 2001 on YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3))
3rd Monday 04/16/ 2M =DATE(YEAR(B1),MONTH(B1),14+CHOOSE(WEEKDAY(DATE
of Month 2001 on (YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3))
4th Monday 04/23/ 2M =DATE(YEAR(B1),MONTH(B1),21+CHOOSE(WEEKDAY(DATE
of Month 2001 on (YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3))
5th Monday 04/30/ 2M =IF(MONTH(DATE(YEAR(B1),MONTH(B1),28+
of Month 2001 on CHOOSE(WEEKDAY(DATE(YEAR(B1),
MONTH(B1),1)),2,1,7,6,5,4,3)))=MONTH(B1), DATE(YEAR(B1),MONTH(B1),
28+CHOOSE( WEEDATE(YEAR(B1),MONTH(B1),1)),2,1,7,6,5,4,3)),"none")
3rd Wed. of 04/18/ 4W =B1-DAY(B1)+22 -WEEKDAY(B1-DAY(B1)+4 ) -- Daniel M.
Month 2001 ed
Last Monday 04/30/ 2M =DATE(YEAR($B$1),MONTH($B$1)+1,1)-
of Month 2001 on WEEKDAY(DATE(YEAR($B$1),MONTH($B$1)+1,6))
see Date
Calculations
Previous 04/09/ 2M =B1-CHOOSE(WEEKDAY(B1,1),6,7,1,2,3,4,5)
Monday 01 on
For a different day of the week rotate the 2nd to last parameters in CHOOSE.
i.e. 7,6,5,4,3,2,1 for Wednesday instead of 2,1,7,6,5,4,3 for Monday as used in some of the
formulae.
Formula in C1 & D1, =IF(ISNUMBER(B1),WEEKDAY(B1),"")
downward
Formula in E1, =personal.xls!getformula(E1) see documentation for this User
downward Defined Function (UDF) in Formula.htm
Weekday(date,1) week starts on Sunday (US default)— Numbers 1 (Sunday) through 7
(Saturday). Weekday(date,2) week starts on Monday — Numbers 1 (Monday) through 7
(Sunday).
Additional formulae and formulae with similar purpose can be found on my Date Calculations
page.
Week beginning on Monday, will assume Sunday belongs to the previous week of.
Format column B as mm/dd/yyyy and column C as ddd. Column C should only show “Mon”.
A2: =TODAY()
B2: =A2-MOD(A2-2,7)
C2: =B2
Created by www.excelvbaclinic.com
Page 17
DATE & TIME
Works for numbers or text in the form yyddd, where yy is the year and ddd is the day within
year.
i.e. 98003, 99003, 00003, 3, 01003, 1003.
=DATE(IF(INT(A1)>39000,INT(A1/1000)+2000,INT(A1/1000)),1,MOD(A1,1000))
These are, of course, the IBM computing “Julian dates”. The real Julian dates are another matter
they begin January 1, 4713 BCE (on the old Julian calendar).
You can specify how you want the filling to be done if use the RtMouse button instead of the
LtMouse button when you use the fill handle to drag your selection down. After dragging you
will be asked what you want to do.
|| copy values, fill series, fill formats, fill values||
|| fill days, fill weekdays, fill months||
|| Linear trend, Growth Trend, series ... || with other choices where applicable.
More information concerning fill-handle.
Ordinal number, any of the numbers first, second, third, etc. (in distinction from one, two, three,
etc. which are called cardinal numbers. Also ordinal numeral.
21st and other dates with numbers as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, etc.
21st May, 1999 and other dates with days of month as 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th,
10th, 11th, etc.
or as a Function
Created by www.excelvbaclinic.com
Page 18
DATE & TIME
Function OrdDate(arg)
dd = Day(arg)
mmmm = Format(arg, "mmmm") '*Corrected*
yyyy = Year(arg)
Select Case Day(arg)
Case 1, 21, 31
OrdDate = dd & "st " & mmmm & ", " & yyyy
Case 2, 22
OrdDate = dd & "nd " & mmmm & ", " & yyyy
Case 3, 23
OrdDate = dd & "rd " & mmmm & ", " & yyyy
Case 4 To 20, 24 To 30
OrdDate = dd & "th " & mmmm & ", " & yyyy
End Select
End Function
A macro by Ron Rosenfeld (see thread) changes the format rather than the text. The macro is
written for XL97 and has an advantage in not using a second cell to display a text format.
Written as a Worksheet_Change macro it will change the format for all dates on a particular
worksheet when they are entered, changed or recalculated. The big advantage is that the cell can
continue to be treated as a numeric value.
Create a new worksheet one week of dates down Column A. Dates created for the current week.
Example run on Fri 12/29/2000. Constants for dates are generated not formulas with date
functions.
Option Explicit
Sub Macro39()
Sheets.Add
Range("1:1,A:A").Font.Bold = True A B
Columns("A:A").Select 12/24/00
Selection.NumberFormat = "ddd mm/dd/yyyy"
1
- 12/30/00
Range("a2").Formula = Int(Now()) _
- Weekday(Int(Now())) + 1
2 Sun 12/24/2000
Range("A2").AutoFill _ 3 Mon 12/25/2000
Destination:=Range("A2:A8"), _ 4 Tue 12/26/2000
Type:=xlFillDefault
Range("a1").Formula = _
5 Wed 12/27/2000
Format([a2], "mm/dd/yy") & Chr(10) _ 6 Thu 12/28/2000
& " - " & Format([a8], "mm/dd/yy") 7 Fri 12/29/2000
Columns("A:A").EntireColumn.AutoFit
Range("B2").Select 8 Sat 12/30/2000
ActiveSheet.Name = "D." & Format([a2], _
"yyyymmdd") 'rename sheet
Created by www.excelvbaclinic.com
Page 19
DATE & TIME
End Sub
The following formula was posted by Laurent Longre (1999-08-10), D is the date.
=INT((D-SUM(MOD(DATE(YEAR(D-MOD(D-2,7)+3),1,2),{1E+99,7})*{1,-1})+5)/7)
In Europe weeks begin on a Monday and end on Sunday, even so the formula
=WEEKNUM(date,2) which indicates that weeks begin on Monday will not work for European
usage. In the US the first week begins on January 1st, so the first week and the last week of a
year may both have less than 7 days.
In the European style (ISO 8601) the week begins on a Monday and includes the first Thursday
of the new year. The reason for Thursday is that the majority of the days in the Mon-Sun week
will be in the new year. This is the same as saying the week with Jan 4th will always be the first
week.
For additional information see “A Summary of the International Standard Date and Time
Notation” at http://www.cl.cam.ac.uk/~mgk25/iso-time.html which contains information on ISO
8601 and references additional material. Also see Pat McCotter's posted an article 1999->03-
>20.
Chip Pearson has followed this more closely you can find out more about week numbers,
including English postal service on Chip’s site.
Created by www.excelvbaclinic.com
Page 20
DATE & TIME
A B C D E F G
1 Format--> General General [h]:mm 0.00
2 Employee Start End Duration Hours =GetFormulaD(address)
3 Jan H. 8:20 10:55 2:35 2.58 D3: =C3-B3+(B3>C3) E3: =24*D3
4 Pat T. 10:55 8:20 21:25 21.42 D4: =C4-B4+(B4>C4) E4: =24*D4
The formula to subtract times where the ending time might look like an earlier time would be:
=C3-B3+(B3>C3)
The last part is a logical expression that adds 1 if start time is greater than end time, or 0
otherwise. Time is measured in days so the addition of 1 is adding 24 hours to the equation.
You subtract one time from the other. The result should be formatted as time but since you
might end up with more than 24 hours you would format as [h]:mm instead of h:mm
Created by www.excelvbaclinic.com
Page 21
DATE & TIME
Remember time is stored as days, so one quarter hour is 1/(24*4) days or .01041666 days. The
fraction will be more accurate. MROUND is part of the Analysis Toolpak Add-in.
Rounding to nearest quarter hour: =MROUND(A22,1/(24*4))
Rounding down to nearest quarter hour: =FLOOR(A22,1/(24*4))
Rounding Up to nearest quarter hour: =CEILING(A22,1/(24*4))
Rounding Up to nearest half hour: =CEILING(A22,1/(24*2))
C D E F G H I J
Rounded Billed @
8 hh:mm HRS Rate/HR Addr Formula
hh:mm $100/HR
9 4:06 4:30 4.5 100.00 $ 450.00 C9 0.170833333333333
10 7:29 7:30 7.5 100.00 $ 750.00 D9 = ROUNDUP(C9*48,0)/48
11 7:31 8:00 8.0 100.00 $ 800.00 E9 = ROUNDUP(C9*48,0)/2
12 8:00 8:00 8.0 100.00 $ 800.00 F9 100
13 37:30 37:30 37.5 100.00 $ 3,750.00 G9 =F9 * ROUNDUP(C9*48,0)/2
Wages calculation with C9 having a time in hh:mm and you want to round up at 1/2 hour
intervals shown in D9. Column C is formatted as [hh]:mm
Time is measured in days, 24 hours in 1 day. The roundup calculation does not handle fractions
so multiply 24 by 2 get the roundup and then divide by 2
The basic concept is: number of hours before core hours + number of hours after core hours
=IF(Shift_Start<Core_Start, Core_Start-Shift_Start,0) + IF(Shift_End>Core_End, Shift_End-
Created by www.excelvbaclinic.com
Page 22
DATE & TIME
Core_End,0)
but since time is not recorded with the dates this becomes more complicated.
> -- corrections to formulas 2002-02-09 to fix errors when converted to
HTML---
> c3: =B3-A3+(A3>B3) is equivalent to =IF(B3>A3,B3-A3,B3-A3+1)
> d3: =IF(B3>=A3,MAX(MIN(B3,G3)-A3,0)+MAX(B3-H3,0), MIN(B3+1,1+G3)-
MAX(A3,H3))
> e3: =IF(ABS(D3-F3)<0.0001,"yes","NO")
> f3: is the goal, it is what is to be expected from the calculations
>
> G3 is the Core.start time
> H3 is the Core stop time
>
> Don't know if this is a concern or not: If clock time goes through
> midnight and core start and stop times it will be incorrect, but your
> elapsed hours would exceed 16 hours as seen in my last tested values.
>
> David McRitchie (1999/08/01)
>
> Tested example:
> --A-- --B-- --C-- --D-- -E- --F-- --G-- --H--
> Start Stop Elap calc. ^^^ GOAL c.start c.ent
> 23:00 07:00 08:00 08:00 yes 08:00 07:00 15:00
> 00:00 08:00 08:00 07:00 yes 07:00 07:00 15:00
> 03:00 11:00 08:00 04:00 yes 04:00 07:00 15:00
> 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00
> 16:00 00:00 08:00 08:00 yes 08:00 07:00 15:00
> 12:00 20:00 08:00 05:00 yes 05:00 07:00 15:00
> 23:00 15:00 16:00 08:00 yes 08:00 07:00 15:00
> 00:00 16:00 16:00 08:00 yes 08:00 07:00 15:00
> 03:00 19:00 16:00 08:00 yes 08:00 07:00 15:00
> 12:00 04:00 16:00 13:00 yes 13:00 07:00 15:00
> 16:00 08:00 16:00 15:00 yes 15:00 07:00 15:00
> 00:00 16:00 16:00 08:00 yes 08:00 07:00 15:00
> 04:00 20:00 16:00 08:00 yes 08:00 07:00 15:00
> 08:00 00:00 16:00 09:00 yes 09:00 07:00 15:00
> 12:00 04:00 16:00 13:00 yes 13:00 07:00 15:00
> 16:00 08:00 16:00 15:00 yes 15:00 07:00 15:00
> 20:00 12:00 16:00 11:00 yes 11:00 07:00 15:00
> 00:00 16:00 16:00 08:00 yes 08:00 07:00 15:00
> 04:00 04:01 00:01 00:01 yes 00:01 07:00 15:00
> 08:00 08:01 00:01 00:00 yes 00:00 07:00 15:00
> 04:00 04:00 00:00 00:00 yes 00:00 07:00 15:00
> 06:00 05:00 23:00 14:00 NO 15:00 07:00 15:00 == failed should be 15 hours
not 14 hours.
>
> Similar information in a little different format, basically switch usage of
G & H columns.
>
> Rate ---> 1 1.5 Extra paid hours
> Start End Norm. Prem. -- -- Extra Pay hours
> Time Time Hours Hours -- -- From To
> 17:00 01:00 03:00 05:00 -- -- 20:00 6:00
> 01:00 09:00 08:00 05:00 -- -- 20:00 6:00
> 09:00 17:00 08:00 00:00 -- -- 20:00 6:00
Created by www.excelvbaclinic.com
Page 23
DATE & TIME
> 17:00 01:00 08:00 05:00 -- -- 20:00 6:00
> 01:00 09:00 08:00 05:00 -- -- 20:00 6:00
> 09:00 17:00 08:00 00:00 -- -- 20:00 6:00
>
> C3: =B3-A3+(A3>B3)-D3
> D3: =IF(B3>=A3,MAX(MIN(B3,H3)-A3,0)+MAX(B3-G3,0), MIN(B3+1,1+H3)-
MAX(A3,G3))
>
> To show time as a hours with decimal fraction multiply Excel hours by 24.
------
The following formula was posted 2002-02-09 by Daniel Maher and fixes a problem that I
indicated in the first example. This solution is for the second example. Will at least be
including this until I fix my own formula. DanielM 2002-02-09
A B C D E
out
=IF(CheckOut>=CheckIn,MAX(0,MIN(CheckOut,UpperB reporte in
ound)- IN OUT of
1 d core
MAX(CheckIn,LowBound)),MAX(0,UpperBound- core
MAX(CheckIn, 14:0 6:00
LowBound))+MAX(0,MIN(CheckOut,UpperBound)- 6:00 8:00 2:00
2 0
LowBound))
12:0 4:00
0:00 12:00 8:00
For the time OUTSIDE the boundaries 3 0
of [LowBound ... UpperBound], it is 12:0 6:00
=(checkout<checkin)+CheckOut-CheckIn- 0:00 12:00 6:00
4 0
Big_Formula_Above
18:0 1:00 14:0
9:00 15:00
If you want the HOURS, multiply by 24. 5 0 0
23:0 12:0 4:00
13:00 9:00
6 0 0
C2: =(B2<A2)+B2-A2
D2: =IF(B2>=A2,MAX(0,MIN(B2,"18:00")-MAX(A2,"8:00")),MAX(0,"18:00"-
MAX(A2,"8:00"))+MAX(0,MIN(B2,"18:00")-"8:00"))
E2: =(B2<A2)+B2-A2 - D2
Total core hours (9AM-5PM) between two datetimestamps, but only weekdays
I would like to calculate the difference in minutes between two dates, excluding the hours
between 5pm to 8am and weekends. For example if the
Created by www.excelvbaclinic.com
Page 24
DATE & TIME
first date is 08/04/99 6:00pm and the end date is 08/05/99 9:00 am, I would like it to calculate as
60 minutes or one hour.
You can use the NETWORKDAYS function from the Analysis Tool.
A1 your first date and B1 your end date, both in full format mm/dd/yy hh:mm
You can have A1 and B1 separated with as many days you want.
The total time is in C1 (formatted with [h]:mm ) :
You might want to use notepad to eliminate end of line characters from these formulas:
A B
Sat
1 12/01/200 Mon 12/03/2001 16:00
1 07:00
2 =A6+A4 =A8+A6
3
4 8:00 Length of core hours for one day
5 7:00 start time (doesn’t count until either 8AM or 9AM) on 1st day
6 16:00 end time (one hour short on 9AM-5PM) on last day
12/01/200
7 start date
1
12/03/200
8 end date
1
9
1
07:00 Original Formula with NETWORKDAYS 9:00 - 17:00 original
0
1
08:00 Original Formula with NETWORKDAYS but 8:00-16:00 instead of 9:00-17:00
1
1
23:00 Formula without NETWORKDAYS corrected to use 9AM to 5PM
2
1 Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in
24:00
3 formula removed)
1 Formula without NETWORKDAYS corrected to use 8AM to 4PM (spaces in
24:00
4 formula removed)
1
Formulas used in A9:A12 note 8 hour interval, with specific time range
5
=MIN("8:00",MAX("0:00","17:00"+INT(A1)-
1 A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"9:00"-
07:00
6 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B
1)-2)-(INT(INT(A1)/INT(B1))))
=MIN("8:00",MAX("0:00","16:00"+INT(A1)-
1 A1))*NETWORKDAYS(A1,A1)+MIN("8:00",MAX(B1-"8:00"-
08:00
7 INT(B1)))*NETWORKDAYS(B1,B1)+"8:00"*(MAX(0,NETWORKDAYS(A1,B
1)-2)-(INT(INT(A1)/INT(B1))))
Created by www.excelvbaclinic.com
Page 25
DATE & TIME
=MIN("8:00",MAX("0:00","17:00"+INT(A1)-A1)) +MIN("8:00",MAX(B1-
1
23:00 "9:00"-INT(B1))) +"8:00"*(MAX(0, INT(B1)-INT(A1)+1)-2)-
8
(INT(INT(A1)/INT(B1)))
=MIN("8:00",MAX("0:00","16:00"+INT(A1)-A1))+MIN("8:00",MAX(B1-
1
24:00 ""8:00""-INT(B1)))+"8:00"*(MAX(0,INT(B1)-INT(A1)+1)-2)-
9
(INT(INT(A1)/INT(B1)))
2 =MIN(A4,MAX("0:00","16:00"+INT(A1)-A1))+MIN(A4,MAX(B1-"8:00"-
24:00
0 INT(B1)))+A4*(MAX(0,INT(B1)-INT(A1)+1)-2)-(INT(INT(A1)/INT(B1)))
Lotus 1-2-3 transition options interfere with entry of date and times, would suggest
turning them off after all you are using Excel not 1-2-3.
Under Tools --> Options --> Transition turn off everything that says transition, and hit
the [OK] button
The DateWatch utility (or a similar 3rd-party program) can cause problems with entering
fractions, it appears under tools menu as “Date Migration”, and can be turned off through
Tools/Addins menu. Rob Bovey 1999->01->15 <uVKu548X GA.205@cppssbbsa04>
Entering stock prices as 1/2 or 1/64 and getting dates: Solution enter 0 1/2 or 0 1/64
instead. See Pasting fractional stock prices show up as dates in Excel for an attempt at
fixing.
Countdown to the New Millennium (year 2001). Some additional Excel 2000 tips.
=DATEVALUE("1-January-2001")-TODAY()&" days remaining in 2000"
Refer to your VBA HELP file for more information. VBA Help is obtained where you can edit
your code. In XL97 and up it is Alt+F11, then F1, and in XL95 invoke F1 (Help) when editing a
module sheet.
Date Returns a Variant (Date) containing the current system date.
DateDiff DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])
Don’t confuse this with the DATEDIF Worksheet Function
DateSerial DateSerial(year, month, day)
DateValue DateValue(date) -- MyDate = DateValue("February 12, 1969")
Created by www.excelvbaclinic.com
Page 26
DATE & TIME
Day Day(date)
Hour Hour(time) -- returns integer between 0 and 23
IsDate IsDate(expression) -- returns True or False
Minute Minute(time) -- returns 0 to 59
Month Month(date)
Now Now -- Returns a Variant (Date) specifying the current date and time according your
computer’s system date and time.
Second Second(time) -- returns whole number between 0 and 59, inclusive
TimeSerial TimeSerial(hour, minute, second)
TimeValue TimeValue(time) -- MyTime = TimeValue("4:35:17 PM")
Weekday Weekday(date, [firstdayofweek])
Year Year(date)
If you want absolute control over adding a number of months to another date where the day of
the month of the first date does not exist in the date that is xx months later.
Sub Ratman02()
Cells.Interior.ColorIndex = 0 'reset
all interior color
Dim cell As Range
This example was tested on 08/05/2000 (Aug
For Each cell In Application.Intersect
5, 2000 US Format) _
A B C D (Selection, ActiveSheet.UsedRange)
10 If IsDate(cell) Then
If cell.Value > Date Then
11 08/01/2000 cell.Interior.ColorIndex = 3 'Red
12 09/01/2000 08/05/2000 - FUTURE DATE
13 08/05/2000 10/01/2000 Else
cell.Interior.ColorIndex = 8 'Cyan
14 08/05/2000 08/05/2000 -- valid date
15 08/05/2000 Hello End If
Else: cell.Interior.ColorIndex = 14
16 08/05/2000 08/05/2000 'Teal -- NOT a Date
17 End If
Next cell
End Sub
More information on Colors in Excel and the
Created by www.excelvbaclinic.com
Page 27
DATE & TIME
If the Text dates and your Regional Dates are both US date format, for a manual conversion:
- Copy an empty cell
- Select Range for cells to be converted
- Edit, Paste Special, Add
- Format range as Date
An alternative is to copy a cell with number “1“ and use Paste Special with Multiply, but it will
cause empty cells to become zeros, so should not be used.
Use of a macro simply needs to reassign the value and Excel will recognize it as a date. (only if
your date formats are US)
Sub MakeTrueDate()
'Converts Text Dates(US) to dates(US), Tom Ogilvy, 2001-03-24 programming
Dim rng As Range
Set rng = Intersect(ActiveCell.EntireColumn, _
ActiveSheet.UsedRange) 'next assume first row is a header
Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1)
rng.NumberFormat = "mm/dd/yyyy"
rng.Value = rng.Value
End Sub
Converting Text Entry Dates to Excel Dates with Text to Columns (#t2cols)
What to do when Text Entry Dates Do NOT Match your Regional Settings
Converting Text entry dates to Excel dates is easily done by multiplying by 1, but when the date
entries do not match your regional settings you can use Text to Columns to fix up your dates.
Actually this would be more of a problem for those with UK/European/Australian dates than
those with US dates. My dates are US and my Regional short date is mm/dd/yyyy which having
US dates is assumed to be m/d/y. If you specify a month greater than twelve, Excel will assume
you reversed the day and month -- there is such an example below. This question was raised by
someone in Australia working with MetaStock which generates an Excel spreadsheet with US
text dates instead of UK/Australian dates.
A B C D E F
Single column processed with
1 Original Specified format for F3:G8
Text to Columns
Text to
2 (source) MDY DMY MDY DMY
Columns
Format on
3 @ m/d/yy m/d/yy ddmmmyyyy Ddmmmyyyy
row 4
4 Date 4/5/99 04/05/1999 05/04/1999 05Apr1999 04May1999
Created by www.excelvbaclinic.com
Page 28
DATE & TIME
UNIX maintains date and time as seconds past Jan 1, 1970. Convert to Excel use
with
= DATE(1970, 1, 1) + (A1/24/60/60)
More information J.E. McGimpsey, 2001-09-26and function.
Regional settings and cell formatting can cause problems with dates if anything is incorrectly
applied. This topic is to help you identify what you actually have.
One thing you can do to quickly determine if entries are Text or Numbers is to use: Select ALL
cells (Ctrl+A), Edit (Ctrl+G), [Special], GoTo, Number & Constants (only constants)
Dates are Numbers. The format for a number can be changed at any time to another number
format. Data that was entered as text or with a text format must be reentered if the format is
changed to a number format.
By formatting the cell range, then reentering the value you can convert text entries containing
numbers to number constants. The fastest way to reenter a single cell is to select cell, press F2,
then Enter.
You can convert a lot of text entries containing numbers to number constants by multiplying by 1
or by adding a blank (truly empty) cell. Select empty cell and copy (ctrl+c) then select the range,
then edit, paste special, add. You can effect a similar change by selecting a cell with a value of
1, copy (ctrl+c), select the range to be affected, paste special, multiply.
You can use one of the REENTER macros on my Reformat page (join.htm) to speed up the
process, there are several variations there, including TrimALL which specifically converts
CHAR(160) which is the HTML symbol (non breaking space) to a space then trims
spaces from the left and right sides of the cell value.
Created by www.excelvbaclinic.com
Page 29
DATE & TIME
Regional Dates in use are US: short: mm/dd/yyyy long: mmmm dd, yyyy
-- Some entries (E16:E25) below have formats overridden in cell.
D
A B C E F G
DATE
1 Display Formula
ENTRY
The Example to the left has entry as
06/07/199 Entered as 6/7/99 with US Regional
2 6/7/99 and my
9 Settings
Regional Settings are for the US, but my
06/07/199 short date
3 5 =LEN(A3)
9 regional setting is modified to include
06/07/199 =TEXT(A4,"General") the full 4 digit
4 36318
9 year so my Regional Setting Short Date
06/07/199 07 Jun =TEXT(A5,"dd mmm format is
5
9 1999 yyyy") mm/dd/yyyy -- interestingly the format
06/07/199 Jun 07, =TEXT(A5,"mmm dd, shows as
6
9 1999 yyyy") m/d/yy because that is the default US
06/07/199 regional setting.
7 TRUE =ISNUMBER(A7)
9
06/07/199 Note cell B35 has code 0160 simulating
8 D4 =CELL("format",A8) an HTML
9
06/07/199 symbol of (non breaking space).
9 v =CELL("type",A9)
9
10 06/07/199 When trying to debug date entries note
36318 =getformula(A10) what you see
9
1) in the formula bar
11 06/07/199
m/d/yy =getformat(A11) 2) in the cell
9
3) in the format (Format, cell)
12 06/07/199 =CODE(RIGHT(A12,
56
9 1))
13
TEXT
14 DATE Display
Display Formula ENTR Formula
ENTRY
Y
15 Entered with quote on Formula
06/07/99 Entered as shown on Formula bar 6/7/99
bar
16 07/06/199
5 =LEN(A16) 6/7/99 6 =LEN(E16)
9
17 07/06/199 =TEXT(A17,"General" =TEXT(E17,"General"
36318 6/7/99 36318
9
18 07/06/199 07 Jun =TEXT(A18,"dd 07 Jun =TEXT(E18,"dd mmm
6/7/99
9 1999 mmm yyyy") 1999 yyyy")
19 07/06/199 Jun 07, =TEXT(A18,"mmm Jun 07, =TEXT(E18,"mmm
6/7/99
9 1999 dd, yyyy") 1999 dd, yyyy")
Created by www.excelvbaclinic.com
Page 30
DATE & TIME
20 07/06/199
TRUE =ISNUMBER(A20) 6/7/99 FALSE =ISNUMBER(E20)
9
21 07/06/199 =CELL("format",A21) =CELL("format",E21)
D1 6/7/99 G
9
22 07/06/199
v =CELL("type",A22) 6/7/99 l =CELL("type",E22)
9
23 07/06/199
36318 =getformula(A23) 6/7/99 6/7/99 =getformula(E23)
9
24 07/06/199 dd/mm/yyy Genera
=getformat(A24) 6/7/99 =getformat(E24)
9y l
25 07/06/199 =CODE(RIGHT(A25, =CODE(RIGHT(E25,
56 6/7/99 57
9 1)) 1))
26
has
Colum
27 Char(160 Display
Display Formula n is Formula
)
Text
so is text
28
06/07/99 has Char(160) 6/7/99 Entered into Text field
29
06/07/99 9 =LEN(A28) 6/7/99 6 =LEN(E28)
30 =TEXT(A30,"General" =TEXT(E30,"General"
06/07/99 06/07/99 6/7/99 36318
31 =TEXT(A31,"dd 07 Jun =TEXT(E30,"dd mmm
06/07/99 06/07/99 6/7/99
mmm yyyy") 1999 yyyy")
32 =TEXT(A31,"mmm Jun 07, =TEXT(E30,"mmm
06/07/99 06/07/99 6/7/99
dd, yyyy") 1999 dd, yyyy")
33 =CELL("format",A33) =CELL("format",E33)
06/07/99 D1 6/7/99 G
34
06/07/99 l =CELL("type",A34) 6/7/99 l =CELL("type",E34)
35
06/07/99 FALSE =ISNUMBER(A35) 6/7/99 FALSE =ISNUMBER(E35)
36
06/07/99 06/07/99 =getformula(A36) 6/7/99 6/7/99 =getformula(E36)
37 dd/mm/yyy
06/07/99 =getformat(A37) 6/7/99 @ =getformat(E35)
y
38 =CODE(RIGHT(A38, =CODE(RIGHT(E36,
06/07/99 160 6/7/99 57
1)) 1))
Created by www.excelvbaclinic.com
Page 31
DATE & TIME
You cannot specify boldface in regular cell formatting. Conditional Formatting could do the
boldface but that is all. A macro is needed to change the time and formatting so that that 1:00
and 13:00 both appear as 1:00 with the PM appearing in bold, and both without AM or PM.
Example:
Original Bus Schedule Sheet New Bus Schedule Sheet
A B C D A B C D
3 8:00 Point B 7:00 Point F 3 8:00 Point B 7:00 Point F
4 12:00 Point C 12:00 Point E 4 12:00 Point C 12:00 Point E
5 13:00 Point D 16:00 Point D 5 1:00 Point D 4:00 Point D
6 17:00 Point E 17:00 Point C 6 5:00 Point E 5:00 Point C
A more complete example with code can be seen on Bus Schedule page
A B C D E F G H I J K L M N O P Q R S T U
7 NAME HRS 8 9 10 11 12 13 14 15 16 17
8 Arlene 7.5 XX X X X XX X X XX X X X X
9 Betty 7.0 X X X X XX X X X XX X X X
10 Cathy 7.5 X X XX X X X X X XX X X XX
11 Coverage 1 1 2 3 3 3 3 2 2 2 3 2 2 2 3 3 3 3 1
B8: =COUNTA($C8:$U8)*0.5
C11: =COUNTA(C$8:OFFSET(C11,-1,0))
Conditional formatting for the range C8:U10
CF1: =COUNTA(C8)
CF2: =NOT(COUNTA(C8))
The difference in days between the two systems is 1462, which you may encounter if you try to
change the date system in a workbook, or if you copied a worksheet from another workbook.
Tools, Options, Calculation, 1900/1904 Dates
Sometimes someone wants a real-time clock in their worksheet. Personally I think the System
time in the corner of the screen serves this purpose, and there are shortcuts for entering System
Date/Time into a Cell or within code. The solution here will produce screen blinking as the
clock updates at one second intervals which may differ by up to one second from the system
clock in your computer.
Created by www.excelvbaclinic.com
Page 32
DATE & TIME
Here is code for a clock that runs in worksheet one, cell A1, unless You
type X in B1, then it stops. Modify location and criteria&rsquos for Your
own use.
Sub clock()
If ThisWorkbook.Worksheets(1).Range("B1").Value = "X" Then Exit Sub
ThisWorkbook.Worksheets(1).Range("A1").Value = Format(Now, "hh:mm:ss AM/PM")
Application.OnTime Now + TimeSerial(0, 0, 1), "clock"
End Sub
Similar to the above. Harold supplied a revised version that recommends use of a start button
and a stop button. Instead of simply replacing the coding I have included both so you can see the
coding. I see the cursor move and blink momentarily every second on XL95. You can create
buttons using the Tools Form bar. The buttons would not ordinarily coincide with cell
boundaries, but they could appear to as in the following example. Again repeating what was said
before: Personally I think the System time in the corner of the screen serves this purpose, and
there are shortcuts for entering System Date/Time into a Cell or within code. A clock on the
worksheet will be stealing cycles whether you see the clock or not, even if the page isn’t
active, and you will probably notice a slow down with large workbooks. You can show
seconds on the Task Bar Clock by using TClockEx without turning your expensive computer
into a wall clock.
Sub clock()
If stopit = True Then Exit Sub
ActiveWorkbook.Worksheets(1).cells(1, 1).Value = _
Format(Now, "hh:mm:ss")
Created by www.excelvbaclinic.com
Page 33
DATE & TIME
Application.OnTime (Now + TimeSerial(0, 0, 1)), "clock"
End Sub
Excel does not have a SLEEP function so you have to calculate the time at which you will
resume. The following will issue three beeps, I give a little more time after the first beep.
I still see timing done with a loop to waste machine cycles. On a mainframe that would be well
over 30 years behind the times. Anyway I think the code I have below will work better across
platforms and more to the point with processors with different speeds instead of a timing loop.
Sub Beeper()
Beep
start2 = Now() + TimeSerial(0, 0, 0.9)
Application.Wait start2
For i = 2 To 3
start2 = Now() + TimeSerial(0, 0, 0.8)
Application.Wait start2
Beep
Next i
End Sub
Stopwatch to time inner processing in seconds. Timer is the number of seconds since
midnight, so a correction has been included for negative number resulting from passing through
midnight during execution. (Limited to duration of 24 hours, longer times possible by including
date) -- also see More on Stop Watches below.
Sub Timing_Test()
Dim timing As Double 'timing will be shown at end
timing = Timer 'Floating point register used
' .... lots of processing here ....
timing = Timer - timing
if timing < 0 then timing = timing + 1440 'midnight correction
MsgBox Format(timing, "0.000") & " seconds"
End Sub
This example will sound an Alarm at a specified time.
Sub Alarm()
Dim beepat As String
Created by www.excelvbaclinic.com
Page 34
DATE & TIME
beepat = InputBox("Give Alarm at", "hh:mm:ss " & _
Format(Now, "mm:hh"), "17:00")
If beepat = "" Then
MsgBox "cancelled"
Exit Sub
End If
Application.OnTime TimeValue(beepat), "BeepMe"
End Sub
Example of a Count Down Timer
Sub CountDownTimer()
Dim beepat As String
beepat = InputBox("Count down Timer hh:mm:ss i.e. 10:00", _
"Time now is " & Format(Now, "hh:mm:ss"), "3:00")
If beepat = "" Then
MsgBox "cancelled"
Exit Sub
End If
Application.OnTime (Now + TimeValue(beepat)), "BeepMe"
End Sub
Sub beepme()
Beep
Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme2"
End Sub
Sub beepme2()
Beep
Application.OnTime (Now + TimeSerial(0, 0, 0.8)), "beepme3"
End Sub
beepme3()
Beep
End Sub
More on Stop Watches -- Continued (#StopWatchcontd), Also take a look at my page on
Slow Response
Inevitably someone is going to try to use Excel to time runners to 100ths of a second. Without
examining whether Excel is really feasible for this or not here are some newsgroup searches on
how to do it. The best solutions will probably require winmm.dll for high resolution. All were
found starting with:
http://groups.google.com/advanced_group_search?q=group:*Excel*&num=100
As text
[a10].Value = Format(Now, "mm/dd/yyyy hh:mm:ss AM/PM")
Range("A11").Value = Format(Now, "hh:mm:ss")
activecell.offset(0,4).value = Format(Now, "hh:mm:ss")
Created by www.excelvbaclinic.com
Page 35
DATE & TIME
John Walkenbach has created as an addin to handle years 0100-9999 in his Extended Date
Functions Add-In, which requires at least XL97. 0100-9999 is the date range supported by
VBA, so don’t know what calendar changes, if any, are actually supported.
I don’t know which calendars are in use in John’s XDATE functions but anything has to be
better than what is builtin to Excel. I will mention the following excerpt from the 1990 “World
Almanac” to highlight some difficulties of working with older dates.
The British Government imposed the Gregorian calendar on all its possessions, including the
American colonies, in 1752. The British decreed that the day following Sept. 2, 1752, should be
called Sep. 14, a loss of 11 days. All dates preceding were marked O.S., for Old Style. In
addition New Year’s day was moved to Jan. 1 from Mar. 25. George Washington’s birth date,
which was Feb. 11, 1731, O.S., became Feb. 22, 1732, N.S.
What is now the US had three different dates for the “Julian” to Gregorian calendar shift alone -
1582 for the areas under Spanish and French control, 1752 for areas under British control, and
1863 for Alaska, when it was purchased from Russia.
I think everyone would agree that that Excel is severely lacking in it’s ability to work with date
calculations such as dates in 1800 especially since there are people living who were born in
1800’s and in treating 1900 as a leap year as had one of it’s predecessors, Lotus 1-2-3.
Time Information, for those who are serious or just interested (#timeinfo)
If you computer clock is consistently off by several minutes when you power up again, you probably have a bad
battery (search: computer clock/CMOS batter*), and should check your OEM site for more information. Replacing
a battery yourself should be a cheap solution.
Official US Time
NIST -- National Institute of Standards and Technology, and
USNO -- US Naval Observatory
See the Public Domain NIST Software area for downloadable synchronization
software. Then if you want to set up with automatic synchronization, choose
an NIST server near you then to have the time synchronize when you start up
your machine add “once” within the Target box in the properties window of
the shortcut
in the \Windows\Start Menu\Programs\Startup folder:
i.e. C:\Internet\Nisttime\nistime-32bit.exe once
I tried automatic synchronization originally, but did not like it, probably useful if you have an
always online connection through a cable, but I prefer to see what the difference actually is, so I
run the program myself each day. Program uses sampling to improve accuracy. If the time gets
way out every day, you will probably have to replace a small battery in your computer.
Outside of the US
http://www.arachnoid.com/abouttime/index.html excellent synchronization.
GMT - Greenwich Mean Time, Universal World Time -- http://greenwich2000.com/
Greenwich 2000 Home Page -- http://greenwich2000.com/
World Time -- http://www.worldtime.com/cgi-bin/wt.cgi
World Time Server anywhere, anytime -- http://www.worldtimeserver.com/ -- get the Atomic
Clock synchronization, perhaps questionable lots of adverts.
Alarm Clock, Turn your $3,000 computer into a $30 Alarm Clock. Karen
Kenworthy, writer for former Windows Magazine, writing their Power User’s
column. [LG]
Clock.exe is supplied with Windows NT, and shows time hh:mm:ss and the date
(but not day of the week). Can be resized for a small display or even a full screen
display. Black text or outlined text on gray background. Choice of local time or
GMT, and can be displayed without title bar.
Created by www.excelvbaclinic.com
Page 37
DATE & TIME
to see seconds, date and more in tray clock, CPU% not displaying on Win2000.
Mouse over shows your customized mini summary, mouse-click a calendar, right-
click more options. Display of time and/or date of your choice and colors on
taskbar. (originally seen in zdnet hotfree downloads)
Title Bar Clock, v1.4 [62k] W9x/2k/XP FREE, {PC clock} TBC displays the day,
month, time, and megabytes of free physical memory in the right side of the Title
Bar of the main window
Something frequently asked in newsgroups is how to place a clock into an Excel
spreadsheet, something you should not do as it will severely affect/curtail your
Excel usage. (see #clock).
Date Information, for those who are serious or just interested (#dateinfo)
Information Please: Today in History, Events that happened on this date in history, world, US
news, current events today calendar timeline. [chronology, almanacs, Homework Center]
Examples
Created by www.excelvbaclinic.com
Page 38
DATE & TIME
Problems (#problems)
###, date column needs to be widened, or cannot have a negative date or time.
dateserial number instead of date, you could be in formula view; otherwise you need
correct formatting.
My DATETIME page appears to have concentrated on formatting dates and times, while Chip
Pearson appears to have concentrated more on calculations in his DATETIME pages. Nothing
remains static on web pages so you may want to recheck pages from time to time. I also have a
Date Calculation page which shows sample calculations in a simulated spreadsheet as a
companion to this page.
DATETIME one of Chip Pearson’s Excel Pages Chip’s site contains a series of
how to’s and macros for dates and times. Additional macros and how to’s can be
found in holidays. Another of Chip’s pages Date And Time Entry for XL97
describes how to enter time or dates without separators -- i.e. 1234 for time entry
12:34. Third Friday of the Month and additional Worksheet Functions For Dates
And Times similar to 4th Monday of a month (above). Scheduling Procedures
With OnTime
Date and Time [Excel] at The Access Web -- Dev Ashish
Time and Date, A guide to time zones, calendars (by Country), sunrise/sunset,
dates on/off daylight savings time. World Clock and Configure your own cities
for time checking.
Since Excel will not accept dates before 1900, DATEDIF() will not work for
dates before 1900.
As previously mentioned John Walkenbach has created as an addin to handle
years 0100-9999 in his Extended Date Functions Add-In, which requires at least
XL97. http://www.j-walk.com/ss/excel/files/xdate.htm and also on John’s site is
Spreadsheet History. Also see XL: Excel Incorrectly Assumes 1900 Is a Leap
Year -- The actual treatment of dates in John’s XDATE functions is that of VBA,
which is better than the treatment found in Excel.
Also of interest
A downloadable employee time sheet can be found in John Walkenbach’s
http://www.j-walk.com/ss/excel/files/index.htm
Obtaining and Changing a File’s Created, Accessed and Modified Dates at Randy
Birch’s “VBnet” (Visual Basic File API Routines) -- this page tells how to
Created by www.excelvbaclinic.com
Page 39
DATE & TIME
obtain/change a file's created, last access, and last modified dates. Identifies five
different times (System Time, Filetime, local systemtime or filetime, MS-DOS,
Windows). For instance Filetime is stored as 100-nanosecond intervals since Jan
1, 1601. (does not specifically relate to Excel). This example allows you to
change the stored times. (functions: GetFileDateString, GetSystemDateString)
Local and GMT Times, Chip Pearson, conversions, the date and time stored as
FILETIME is a Type comprised of two 32-bit Long integers, which together form
a 64-bit integer (not supported in VB/VBA). The value of the FILETIME is the
number of 100-nanosecond intervals since 1-January-1601. Site also has
Conversions between UT and local Daylight Savings time.
Calendars, <B662658A.1A7%[email protected]> site is
http://www.altcal.eu/, AltCal, an Excel spreadsheet to build julian or gregorian
calendars from 4713 BC to ... 1465001 AD, also see Q213795 below.
TimeCore Solo ~ time management for the Individual, 1.5.43 (last freeware
version),(not Excel), {Time management} TimeCore Solo is a time tracking
program with a recording engine that captures time worked on a task or project.
[LockerGnome]
U.S. National Debt Clock : Real Time
World Time Clock
<liMonths of the World, by Rob van Gelder, dates can be formatted to any Country and
explanation of formats that include code like [$-1409]dddd, d mmmm yyyy where the
1409 is LCID hexcode for New Zealand. </li
Calendar control added for entry into active cell from a Calendar, Chip Pearson, 2002-02-
24, misc.
Created by www.excelvbaclinic.com
Page 40