[Rd] How to convert time_t to R date object

Dirk Eddelbuettel edd at debian.org
Mon Mar 17 12:40:54 CET 2014


On 16 March 2014 at 22:24, Sandip Nandi wrote:
| Hi Bill ,
| 
| The following C code  may help you , time_t is typedef to long int 
| 
| SEXP  getTime() {
| 
|   time_t current_time;
|     char* c_time_string;
|     current_time = time(NULL);
|     c_time_string = ctime(&current_time);
| 
|    return mkString(c_time_String); // or if you want to return as int vector
| return scalarInt(current_time);
| }
| 
| If you feel anything wrong , I will be very happy to know . 

That is a) time and not date, and b) formatted as a string.

Dirk

 
| Thanks,
| Sandip
| 
| 
| On Sun, Mar 16, 2014 at 9:54 PM, Bill Wang <freecnpro at gmail.com> wrote:
| 
|     Hi Dirk,
| 
|     Thanks for your reply, I neede convert time_t to R type in C code, can not
|     use Rcpp. Maybe Rcpp source code could help me.
| 
|     Cheers,
|     Bill
| 
| 
|     2014-03-16 22:55 GMT+08:00 Dirk Eddelbuettel <edd at debian.org>:
| 
|     >
|     > On 16 March 2014 at 18:36, Bill Wang wrote:
|     > | I am writing a R extensions, and I need pass time_t to R in C, but I
|     > don't
|     > | know how to do.
|     > | Can you give me some help? do not use double directly.
|     >
|     > Just treat it as an int:
|     >
|     >   R> library(Rcpp)
|     >   R> cppFunction("Date time_t2date(time_t what) { return((int) what); }
|     ")
|     >   R> time_t2date(0)
|     >   [1] "1970-01-01"
|     >   R> time_t2date( Sys.Date() )
|     >   [1] "2014-03-16"
|     >   R>
|     >
|     >
|     > Here I use Rcpp to define the 'time_t2date' function on the fly.
|     >
|     > It takes the time_t and returns a Date type (which here is a C++ Date
|     type
|     > mapping to the R Date -- you can ignore that, but will have to write the
|     > legwork yourself if you don't use Rcpp).
|     >
|     > As 'time_t' is 'long int' on my system, so I cast it to int. The rest is
|     > automagic (thanks to RcpP).
|     >
|     > Notice that I also get today's date down and up correctly.
|     >
|     > See 'Writing R Extensions' for the details at the C level.
|     >
|     > See the Rcpp documentation (and, if I may, my book) for details on Rcpp
|     if
|     > that interests you.
|     >
|     > Dirk
|     >
|     > --
|     > Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
|     >
| 
| 
| 
|     --
| 
|     *Travel | Programming*
|     *http://freecnpro.net* <http://freecnpro.net>
| 
|             [[alternative HTML version deleted]]
| 
|     ______________________________________________
|     R-devel at r-project.org mailing list
|     https://stat.ethz.ch/mailman/listinfo/r-devel
| 
| 

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com



More information about the R-devel mailing list