Tuesday, November 3, 2009

Obtaining Current Date and Time

I had a simple task of adding a time stamp for a resource request. By time stamp I mean the year-date-time when the resource was requested. It was C++ code I did not want to add objective-c code in there. So the option I had was to use Core-Foundation CFDate or to use simple unix calls. I hate Carbon anyways, whenever I get a chance I try avoid it. Same was the case here. I used unix apis. They turned out be simple and did the job with charm.

Code snippet:

time_t currtime;
time(&currtime);

struct tm *dateAndTime = locattime(&currtime);

int year = 1900 + timedate->tm_year;
int month = dateAndTime->tm_mon+1;
int date = dateAndTime->tm_mday;
int hour = dateAndTime->tm_hour;
int min = dateAndTime->tm_min;
int sec = dateAndTime->tm_sec;

Now I can format the time-stamp string in any damn way I want. If objective-c was an option NSDate would have done the job for me.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails