can anyone tell me why R give such outcome below:
> as.POSIXct(\"2013-01-01 08:00\")
[1] \"2013-01-01 08:00:00 HKT\"
> as.Date(as.POSIXct(\"2013-01-01
This happens as documented and previously explained when contemporaneous UTC time is before (your third example) or after midnight on your POSIXct date. To see the math for yourself, inspect as.Date.POSIXct
at the console. The math under the default tz="UTC"
is clear. In the non-default case, R essentially calls as.Date.POSIXlt
, and the date-travel
does not occur. In fact, if you had started with the lt
object you would not have had this problem:
> as.Date(as.POSIXlt("2013-01-01 07:00", tz = "Hongkong"))
[1] "2013-01-01"
The easiest work-around is to call as.Date with tz=""
to force using the less offending as.Date.POSIXlt
algorithm:
> as.Date(as.POSIXct("2013-01-01 07:00"), tz = "")
[1] "2013-01-01"
Use the time zone parameter of as.Date
:
as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"))
#[1] "2012-12-31"
as.Date(as.POSIXct("2013-01-01 07:00",tz="Hongkong"),tz="Hongkong")
#[1] "2013-01-01"
In fact, I recommend always using the tz
parameter when using date-time converting functions. There are other nasty surprises, e.g. with daylight saving time.
The problem here is timezones - you can see you're in "HKT"
. Try:
as.Date(as.POSIXct("2013-01-01 07:00", 'GMT'))
[1] "2013-01-01"
From ?as.Date()
:
["
POSIXct
" is] converted to days by ignoring the time after midnight in the representation of the time in specified timezone, default UTC