Convert character to Date

Hello, I wish to convert character into date. Currently, my date is in format - "03-Apr-2021". I need to get the 1st date of the month 04-01-2021 in date format.

Thanks,

You can first parse it and then put it in appropriate form.

library(lubridate)
a<- "03-Apr-2021"
format(dmy(a), "%m-%d-%Y")
#> [1] "04-03-2021"

The format is what tells the function how to read the input characters.

Let's tell it the pattern of the delimiter.

The days of the week are in the way, so it is best to remove them.

x <- "1-6-2016"
as.Date(x, format = "%m-%d-%Y")
x <- "1_6_2016"
as.Date(x, format = "%m_%d_%Y")
x <- "6_2016-1"
as.Date(x, format = "%d_%Y-%m")
x <- "1/6/2016"
as.Date(x, format = "%m/%d/%Y")

lubridate is a great package that further extends the recognition of the year and month.

library(lubridate)
x <- "1-6-2016"
mdy(x)
x <- "2016,Jan 6"
ymd(x)
1 Like

Hi @piku9290dgp and @mhakanda,
Try this:

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
a <- "03-Apr-2021"
format(dmy(a), "%m-%d-%Y")
#> [1] "04-03-2021"

# Make sure day-of-month = 01
format(dmy(a), "%m-01-%Y")
#> [1] "04-01-2021"

# BUT, beware it's still a "character" string not a "date" object.
class(format(dmy(a), "%m-01-%Y"))
#> [1] "character"

# Make string a date, force the first day-of-month, and then print as required
a_date <- as.Date(a, "%d-%b-%Y")
a_date
#> [1] "2021-04-03"

b_date <- floor_date(a_date, "month")
b_date
#> [1] "2021-04-01"
format(b_date, "%m-%d-%Y")
#> [1] "04-01-2021"

Created on 2021-06-16 by the reprex package (v2.0.0)

2 Likes

You can resolve reading tha date and changing the format

dt_input = "03-Apr-2021"

dt_out = format(as.Date(dt_input, format = "%d-%b-%Y"), format = "%m-01-%Y")
# or  in alternative
dt_out = format(as.Date(dt_input, "%d-%b-%Y"), "%m-01-%Y")

> dt_input
[1] "05-Apr-2021"
> dt_out
[1] "04-01-2021"

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.