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
Use the function strftime
from time.h
strftime(array[index]->mtime, 20, "%d-%b-%Y %H:%M", pmytm);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With