Extract time part from VBA date
- 0
- Add a Comment
In a project at work I use Excel to perform analyses of some data records, which are timestamped by date and time.
I want to categorize the records by their time-of-day eg. “morning” and “afternoon”.
For this I define what is the beginning and end of each category eg. “morning”: from 07:00 to 09:00.
To find the category I simply need to extract the time component from the (date)timestamp of each record and compare to my time-of-day categories.
However I didn’t find a simple “built-in” way to extract the time component from the timestamp field.
I ended up using the following code:
‘ assuming Timestamp is of type date,
‘ perhaps the result of a CDate(TimestampAsString) conversion
TimeComponent = CDate(Format(Timestamp, “HH:mm”))
The code formats the timestamp as a string, taking only the hour and minutes, then converts back into a date. The resulting TimeComponent can then be compared directly with eg. CDate(”07:00″).
