Search code examples
rposixposixctposixlt

R: Posix (Unix) Time Crazy Conversion


Unix time is 1435617000.

as.Date(1435617000,origin="01-01-1970")
[1] "3930586-11-23"

Which is wrong. I'm trying to (a) get the correct date, which, per epoch converter is GMT: Mon, 29 Jun 2015 22:30:00 GMT.

How do I get R to tell me the month, day, year, hour, minute & second? Thank you.


Solution

  • I think the reason why that happen is because as.Date converts arguments to class date objects. In this case you do not need a date but a class POSIXct object because your input, the x vector, contains other informations that as.Date is not able to manage. Another problem that even with the right function could appear, is that if when you do not specify the right time zone with the tz argument (except the case where your time zone is the same as the original time).

    The following code does the job.

    x <- 1435617000
    as.POSIXct(x, origin = "1970-01-01", tz ="GMT")
    [1] "2015-06-29 22:30:00 GMT"
    

    Use as.Date

    Just in the case you wanted only the date but you have a complete Unix time like x, you have to just divide by 86400 (which is the number of seconds in a day!) to get only the right date.

     as.Date(x/86400L, origin = "1970-01-01")
    [1] "2015-06-29"
    

    Another important detail

    The origin argument has to be supplied with YYYY-MM-DD and not like you did DD-MM-YYYY I am not sure but I think that the former is the only accepted and correct way.