Marta Marta - 15 days ago 7
R Question

Convert a date string "yyyy-mm-dd" to milliseconds since epoch

I have some numbers that represent dates in milliseconds since epoch, 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970

1365368400000,
1365973200000,
1366578000000


I'm converting them to date format:

as.Date(as.POSIXct(my_dates/1000, origin="1970-01-01", tz="GMT"))


answer:

[1] "2013-04-07" "2013-04-14" "2013-04-21"


How to convert these strings back to milliseconds since epoch?

Answer

Here are your javascript dates

x <- c(1365368400000, 1365973200000, 1366578000000)

You can convert them to R dates more easily by dividing by the number of milliseconds in one day.

y <- as.Date(x / 86400000, origin = "1970-01-01")

To convert back, just convert to numeric and multiply by this number.

z <- as.numeric(y) * 86400000

Finally, check that the answer is what you started with.

stopifnot(identical(x, z))

As per the comment, you may sometimes get numerical rounding errors leading to x and z not being identical. For numerical comparisons like this, use:

library(testthat)
expect_equal(x, z)