Refactored time function