tags:

views:

60

answers:

2

Hello,

I am getting a struct tm and I want to convert it into a string with this specific output:

dd-mm-yyyy hh:mm

where everything is a number except for the month (mm), such as:

14-Oct-2010 10:35

This is my current code:

  struct stat sb;
  if (lstat(path, &sb) == 0) {
    struct tm *pmytm = gmtime(&sb.st_mtime);
    sprintf(array[index]->mtime, "%d-%d-%d %d:%d", pmytm->tm_mday, pmytm->tm_mon, 1900 + pmytm->tm_year, pmytm->tm_hour, pmytm->tm_min);

The issue is that I don't know how I could transfer this pmytm->tm_mon into the month efficiently. Do you recommend that I build an array of months and just index into that array (replacing %d with %s in my sprintf), or is there a better solution please?

Also, I have an issue with the hours and minutes. If it is below 10 (2 numbers), it will display only one number such as: 10:8 rather than 10:08. How can I please fix that?

Thank you very much for your help,

EDIT: What I have in mind as a solution (is that elegant ?):

  static char *months[] = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

  struct stat sb;
  if (lstat(path, &sb) == 0) {
    struct tm *pmytm = gmtime(&sb.st_mtime);
    sprintf(array[index]->mtime, "%02d-%s-%d %02d:%02d", pmytm->tm_mday, months[pmytm->tm_mon], 1900 + pmytm->tm_year, pmytm->tm_hour, pmytm->tm_min);

Jary

+6  A: 

Use the function strftime from time.h

strftime(array[index]->mtime, 20, "%d-%b-%Y %H:%M", pmytm);
Michał Trybus
How can I specify my output with that function please?
Jary
I added an example. Check the manual for specific formatting.
Michał Trybus
Perfect thank you, that is even more elegant!
Jary
@Jary: Using the format specifiers described in the function documentation: http://www.cplusplus.com/reference/clibrary/ctime/strftime/ - who'd have thought!? ;)
Clifford
A: 

If you want more control of time formatting try using strfime:

struct stat sb;
if (lstat("/etc/passwd", &sb) == 0) {
    char    time_buf[256];
    (void) strftime(time_buf, sizeof (time_buf),
        "%m-%d-%Y %H-%M (mon=%b)", localtime(&sb.st_mtime));
    (void) printf("Time: %s\n", time_buf);
}

You can use gmtime() instead of localtime() if you do not want timezone correction.

The output from this is:

Time: 08-30-2010 17-13 (mon=Aug)
Lee-Man
Thank you very much.
Jary