Marta - 1 year ago 73

R Question

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**