Devin
Devin

Reputation: 323

Converting a list of dates into another format in R?

I am attempting to change these lists into another type of format for use in the RJDBC package. The syntax for Oracle will only accept dates in the format of '1-OCT-18'. However, the output of this list is in the format '2018-10-01'.

How can I convert these lists into the format: 1-OCT-18

   begin <- ymd("2017-01-01")+ months(0:21)
   last <- ymd("2017-02-01")+ months(0:22)-days(1)

Upvotes: 0

Views: 280

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99361

You can use format, wrapping in toupper for upper-case, and trimws to trim the whitespace created by %e. I used %e in format because it is the Day of the month as decimal number (1–31), with a leading space for a single-digit number. So then we just remove the whitespace afterward.

trimws(toupper(format(begin, "%e-%b-%y")))
#  [1] "1-JAN-17" "1-FEB-17" "1-MAR-17" "1-APR-17" "1-MAY-17" "1-JUN-17"
#  [7] "1-JUL-17" "1-AUG-17" "1-SEP-17" "1-OCT-17" "1-NOV-17" "1-DEC-17"
# [13] "1-JAN-18" "1-FEB-18" "1-MAR-18" "1-APR-18" "1-MAY-18" "1-JUN-18"
# [19] "1-JUL-18" "1-AUG-18" "1-SEP-18" "1-OCT-18"

For the last vector, you can omit trimws because %e won't generate any whitespace for two-digit numbers.

toupper(format(last, "%e-%b-%y"))
#  [1] "31-JAN-17" "28-FEB-17" "31-MAR-17" "30-APR-17" "31-MAY-17"
#  [6] "30-JUN-17" "31-JUL-17" "31-AUG-17" "30-SEP-17" "31-OCT-17"
# [11] "30-NOV-17" "31-DEC-17" "31-JAN-18" "28-FEB-18" "31-MAR-18"
# [16] "30-APR-18" "31-MAY-18" "30-JUN-18" "31-JUL-18" "31-AUG-18"
# [21] "30-SEP-18" "31-OCT-18" "30-NOV-18"

Upvotes: 1

Related Questions