Marta
Marta

Reputation: 3843

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?

Upvotes: 3

Views: 4475

Answers (2)

I will provide a simple framework to handle various kinds of dates encoding and how to go back an forth. Using the R package ‘lubridate’ this is made very easy using the period and interval classes.

When dealing with days, it can be easy as one can use the as.numeric(Date) to get the number of dates since the epoch. To get any unit of time smaller than a day one can convert using the various factors (24 for hours, 24 * 60 for minutes, etc.) However, for months, the math can get a bit more tricky and thus I prefer in many instances to use this method.

library(lubridate) as.period(interval(start = epoch, end = Date), unit = 'month')@month

This can be used for year, month, day, hour, minute, and smaller units through apply the factors.

Going the other way such as being given months since epoch:

library(lubridate) epoch %m+% as.period(Date, unit = 'months')

I presented this approach with months as it might be the more complicated one. An advantage to using period and intervals is that it can be adjusted to any epoch and unit very easily.

Upvotes: 0

Richie Cotton
Richie Cotton

Reputation: 121077

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)

Upvotes: 5

Related Questions