Sai A Sai A
Updated date Mar 13, 2024
In this blog, we will learn how to convert strings to dates in C programming. Explore multiple methods, including sscanf() and strptime().

Method 1: Using sscanf() Function

To convert a string to a date in C is by using the sscanf() function. This function parses input from a string based on a specified format and stores the resulting values into variables.

#include <stdio.h>

int main() {
    char dateString[] = "2024-03-05";
    int year, month, day;
    
    sscanf(dateString, "%d-%d-%d", &year, &month, &day);
    
    printf("Year: %d, Month: %d, Day: %d\n", year, month, day);
    
    return 0;
}

Output:

Year: 2024, Month: 3, Day: 5

In this method, we use sscanf() to parse the string dateString using the specified format "%d-%d-%d", where %d indicates integer values separated by hyphens. The parsed values are then stored in the variables year, month, and day, respectively.

Method 2: Using strptime() Function

To use the strptime() function, which converts a string to a struct tm object representing a date and time.

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

int main() {
    char dateString[] = "2024-03-05";
    struct tm tm;
    
    strptime(dateString, "%Y-%m-%d", &tm);
    
    printf("Year: %d, Month: %d, Day: %d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
    
    return 0;
}

Output:

Year: 2024, Month: 3, Day: 5

Here, we use strptime() to parse the string dateString with the format "%Y-%m-%d", where %Y represents the year, %m represents the month, and %d represents the day. The parsed values are stored in the tm structure, and then we retrieve them from the structure.

Method 3: Custom Parsing

If the standard library functions don't meet your requirements, you can implement custom parsing logic to convert strings to dates. This approach gives you full control over the parsing process and allows handling of various date formats.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char dateString[] = "05/03/2024";
    int day, month, year;
    
    sscanf(dateString, "%d/%d/%d", &day, &month, &year);
    
    printf("Year: %d, Month: %d, Day: %d\n", year, month, day);
    
    return 0;
}

Output:

Year: 2024, Month: 3, Day: 5

In this custom parsing method, we define our date format as "dd/mm/yyyy" and use sscanf() to extract the day, month, and year components from the string dateString. This method provides flexibility in handling different date formats.

Comments (0)

There are no comments. Be the first to comment!!!