Home > Backend Development > C++ > How Can I Implement strptime() Functionality on Windows?

How Can I Implement strptime() Functionality on Windows?

Susan Sarandon
Release: 2024-12-22 14:20:11
Original
155 people have browsed it

How Can I Implement strptime() Functionality on Windows?

strptime() for Windows

strptime() is a POSIX function that is commonly used to parse text strings into tm structures. Unfortunately, this function is not available on Windows.

Alternative Implementations

If you are looking for a good equivalent implementation of strptime() for Windows, here is a solution that utilizes the sscanf, struct tm, and mktime functions:

  1. Parse the date using sscanf.
  2. Copy the integers into a struct tm, adjusting for the fact that months are 0-indexed and years start in 1900.
  3. Finally, use mktime to obtain a UTC epoch integer.

Remember to set the isdst member of the struct tm to -1 to avoid daylight savings issues.

Example

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

int main() {
    char *date_str = "MM-DD-YYYY HH:MM:SS";

    struct tm tm;
    sscanf(date_str, "%d-%d-%d %d:%d:%d", &tm.tm_mon, &tm.tm_mday, &tm.tm_year, &tm.tm_hour, &tm.tm_min, &tm.tm_sec);

    tm.tm_mon -= 1;  // Adjust for zero-indexing
    tm.tm_year -= 1900;  // Adjust for 1900 starting year

    time_t epoch = mktime(&tm);

    printf("Epoch: %ld\n", epoch);

    return 0;
}
Copy after login

The above is the detailed content of How Can I Implement strptime() Functionality on Windows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template