Reputation: 3774
Is there a function or an elegant way to convert time to a user friendly time of day string?
For example, if it is 9am right now, then
> time_of_day(Sys.time())
[1] "morning"
If it was 3pm, it would return
> time_of_day(Sys.time())
[1] "afternoon"
Upvotes: 2
Views: 410
Reputation: 389265
I am not aware if such a function exists but it would not be difficult to write one of your own. Here's a way based on hour of the day.
time_of_day <- function(time) {
hr <- lubridate::hour(time)
dplyr::case_when(hr > 6 & hr < 12 ~ 'morning',
hr >= 12 & hr < 16 ~ 'afternoon',
hr >= 16 & hr <= 20 ~ 'evening',
TRUE ~ 'night')
}
time_of_day(Sys.time())
#[1] "morning"
Upvotes: 4
Reputation: 614
Ronak beat me to it, but here's an option using lubridate and an ifelse statement:
time_day <- function(current_time) {
ifelse(am(current_time) == 'TRUE',
'morning',
'afternoon')
}
time_day(Sys.time())
Upvotes: 4