-1

Sorry about another date-question, but I couldn't find an answer. I have a date-type "September 2017" and need to convert it to "30.09.2017" (last day of month — for all months of all years). I've tried:

date <- as.Date(date), "%B %d %Y")

+ variations of %d%m%y

And that:

library(zoo)
date <- as.Date(as.yearmon(date))

But every time I have NA.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
  • 3
    Use `as.Date(paste(30, "September 2017"), format="%d %B %Y")`. You need to include a day. Month Year is not sufficient. – lmo Oct 09 '17 at 16:36
  • 1
    Mind your [locales when using `%B`](https://stackoverflow.com/questions/13726894/strptime-as-posixct-and-as-date-return-unexpected-na). – Henrik Oct 09 '17 at 16:38
  • `> as.Date(paste(01, "September 2017"), format="%d %B %Y") [1] NA` – Ekaterina Kolmakova Oct 09 '17 at 16:51

1 Answers1

2

This works for me:

> library(zoo)
> s = "September 2017"
> as.yearmon(s)
[1] "Sep 2017"

If I then convert to date, it gets the first of the month:

> as.Date(as.yearmon(s))
[1] "2017-09-01"

This seems to be exactly what you are doing but you don't explicitly show us where your "September 2017" string is so I suspect a problem there...

As for the "30th", what are you going to do about February? You can use frac=1 to get the last day of the month (hat tip @Henrik):

> as.Date(as.yearmon(s),frac=1)
[1] "2017-09-30"
> as.Date(as.yearmon("February 2018"),frac=1)
[1] "2018-02-28"
> as.Date(as.yearmon("February 2020"),frac=1)
[1] "2020-02-29"
Spacedman
  • 89,688
  • 12
  • 125
  • 209