[Rd] creating POSIXct dates in C

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Feb 19 07:20:26 CET 2005


I think this is actually about converting from POSIXlt to POSIXct in C.

On Fri, 18 Feb 2005, Whit Armstrong wrote:

> I'm trying to generate POSIXct times in a call to a C function.

Doesn't look like ISO C to me.  Things are easier if you have ISO C99 
functions, but R does not assume them (and virtually no OS had them when 
this was written, and few do now).  You can also use BSD/glibc versions 
with a tz offset, again if you can assume those.

> However, I'm having trouble generating times with the proper offset from
> UTC.
>
> Can anyone offer any help with this issue?
>
> I've looked at R-2.0.1/src/main/datetime.c, but I was not able to find
> an example that I could easily pull from that file.

It is not easy, but it is there.

The conversion from struct tm times to calendar times (POSIXct) is done by
mktime.  How you tell it the timezone is OS-specific, but generally
setting the environment variable TZ is the trick.

> Thanks in advance,
> Whit
>
>
> Here is my example in C:
>
> #include <stdio.h>
> #include <time.h>
>
> int main() {
>  struct tm localtime_tm;
>  struct tm utc_tm;
>
>  time_t localtime_posix;
>  time_t utc_posix;
>
>  char buf[255];
>
>  strptime("1970-01-01", &localtime_tm);
>  localtime_posix = mktime(&localtime_tm);
>
>  // this prints 0
>  // which is what the time would be if we were in GMT
>  // how do we convert this time to our timezone
>  // taking into account that the offset is not
>  // constant, since daylight savings time
>  // will shift the offset by an hour
>  // for certain times
>  printf("%d\n",(double)localtime_posix);
>
>
>  // now convert it to gmtime
>  gmtime_r(&localtime_posix, &utc_tm);
>  utc_posix = mktime(&utc_tm);
>
>  // this still prints 0
>  // how do I convert it to a utc time
>  // representing 1970-01-01 in EST ??
>  printf("%d\n",(double)utc_posix);
>
> }
>
>> R.Version()
> $platform
> [1] "i686-pc-linux-gnu"
>
> $arch
> [1] "i686"
>
> $os
> [1] "linux-gnu"
>
> $system
> [1] "i686, linux-gnu"
>
> $status
> [1] ""
>
> $major
> [1] "2"
>
> $minor
> [1] "0.1"
>
> $year
> [1] "2004"
>
> $month
> [1] "11"
>
> $day
> [1] "15"
>
> $language
> [1] "R"
>
>
> RHEL 3.0
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list