-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformat_POSIXct.R
74 lines (73 loc) · 2.49 KB
/
format_POSIXct.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# DIZtools - Utilities for 'DIZ' R Package Development
# Copyright (C) 2020-2023 Universitätsklinikum Erlangen, Germany
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#' @title Formats a given POSIXct timestamp without the need of manually
#' specifing format parameters.
#'
#' @description See title.
#'
#' @param x The POSIXct timestamp or a string to be automatically
#' converted to a POSIXct timestamp.
#' @param lang (Optional, String, Default = "en") The language of the result.
#' Currently implemented: "en"/"de". If you supply another not yet
#' implemented language here, "en" will be chosen automatically.
#' @param date (Optional, Boolean, Default = TRUE) Should the date be part
#' of the result string?
#' @param time (Optional, Boolean, Default = TRUE) Should the time be part
#' of the result string?
#' @return (String) The formatted timestamp as a string.
#' @examples
#' \dontrun{
#' format_POSIXct(x = "2021-12-31 12:34")
#' ## Result: "2021-12-31, 12:34:00"
#' format_POSIXct(x = "2021-12-31 12:34", lang = "de")
#' ## Result: "31.12.2021, 12:34:00"
#' format_posixct(Sys.time())
#' ## Result: "2022-01-01, 09:10:50"
#' )}
#'
#' @export
#'
format_posixct <- function(x,
lang = "en",
date = TRUE,
time = TRUE) {
x <- parsedate::parse_date(dates = x, approx = FALSE)
res <- ""
seperator <- ", "
if (lang == "de") {
if (date) {
res <- format(x = x, format = "%d.%m.%Y")
}
if (date && time) {
res <- paste0(res, seperator)
}
if (time) {
res <- paste0(res, format(x = x, format = "%H:%M:%S"))
}
} else {
## Default: Lang = "en" (or anything not-defined)
if (date) {
res <- format(x = x, format = "%Y-%m-%d")
}
if (date && time) {
res <- paste0(res, seperator)
}
if (time) {
res <- paste0(res, format(x = x, format = "%H:%M:%S"))
}
}
return(res)
}