get current time and convert it to string

Tydr Schnubbis fake at address.dude
Wed Apr 26 09:48:56 PDT 2006


Abby (J.P.) wrote:
> Hello,
> I want to get current time and put it into a string, I tried this :
> 
> 
> int* the_time;
> std.c.time.time(the_time);
> 
> char* str_time_ptr;
> str_time_ptr = std.c.time.ctime(the_time);
> 
> char[] anwser = "Current time is: " ~ *str_time_ptr;
> 

import std.date;
char[] answer = "Current time is: " ~
                  std.date.toTimeString(std.date.getUTCtime());

Use the Date struct if you want more control over the format.

> 
> But it does only concatenate the first letter of the array return by 
> ctime. I looked for C examples, but they all use printf:
> time_t rawtime;
> time ( &rawtime );
> printf ( "Current date and time are: %s", ctime (&rawtime) );
> 

In D you won't be using zero-terminated strings except for interfacing 
with C functions.  If you dereference a char pointer (like 
*str_time_ptr), you get a char. Just like a you would in C.  If you call 
a C function that returns a pointer to a zero-terminated string, you can 
convert it into a D string like this:

char[] str_timeto = std.string.toString(str_time_ptr);

and the other way around:

char* str_timeto_ptr = std.string.toStringz(str_time);



More information about the Digitalmars-d-learn mailing list