0 Pluspunkte 0 Minuspunkte
Wie arbeitet man mit Datum und Zeit in C?
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Hier ein Beispiel mit den wichtigsten Operationen.

#define _XOPEN_SOURCE 700 // needed for strptime()

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


int main() {

    time_t currentTime = time(NULL);
    printf("Current timestamp: %ld\n", currentTime);

    struct tm* timeInfo = localtime(&currentTime);
    
    // format timestamp
    char formattedTime[50];
    strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", timeInfo);
    printf("Formatted time: %s\n", formattedTime);
    
    // manipulating
    timeInfo->tm_mday += 1;
    mktime(timeInfo); // Normalize the date
    strftime(formattedTime, sizeof(formattedTime), "%Y-%m-%d %H:%M:%S", timeInfo);
    printf("Updated time: %s\n", formattedTime);
    
    // scan a timestamp
    const char* dateString = "2023-07-09 21:20";
    strptime(dateString, "%Y-%m-%d %H:%M", timeInfo);
    time_t timestamp = mktime(timeInfo);
    printf("Timestamp: %ld\n", timestamp);

    // change timezone
    const char* newTimezone = "America/New_York";
    setenv("TZ", newTimezone, 1);
    tzset();
    printf("Current datetime in New York: %s", ctime(&currentTime));
    
}
von (776 Punkte)