How to convert only the date without time to a string in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>

/*
    Function: dateToString
    Purpose : Convert a struct tm date to a string (YYYY-MM-DD)
*/
void dateToString(const struct tm* t, char* buffer, size_t size) {
    strftime(buffer, size, "%Y-%m-%d", t);  // Only date
}

/*
    Function: makeDate
    Purpose : Build a struct tm from integers (year, month, day)
*/
struct tm makeDate(int y, int m, int d)
{
    struct tm t = {0};
    t.tm_year = y - 1900;   // years since 1900
    t.tm_mon  = m - 1;      // months since January (0–11)
    t.tm_mday = d;          // day of month
    mktime(&t);             // normalize (fills weekday, etc.)
    
    return t;
}

int main()
{
    char buffer[32] = "";

    // ---------------------------------------------------------
    // 1. Today's date
    // ---------------------------------------------------------
    time_t now = time(NULL);
    struct tm* today = localtime(&now);

    dateToString(today, buffer, sizeof(buffer));
    printf("Today's date is: %s\n", buffer);

    // ---------------------------------------------------------
    // 2. Hard-coded date
    // ---------------------------------------------------------
    struct tm myDate = makeDate(2025, 12, 7);
    dateToString(&myDate, buffer, sizeof(buffer));
    printf("Hard-coded date is: %s\n", buffer);

    return 0;
}



/*
run:

Today's date is: 2026-05-30
Hard-coded date is: 2025-12-07

*/

 



answered 9 hours ago by avibootz

Related questions

...