C语言获取当前日期和时间

一、前言

  本文介绍使用C语言获取系统当前的日期和时间,包括Linux和Windows环境下的不同函数使用。同时,使用自己编写的获取日期和时间的函数自定义实现延时函数的功能。

二、相关函数介绍及代码实现

2.1、Linux下的相关函数

(1)函数 void ftime(struct timeb *tp);

头文件:#include <sys/timeb.h>
说明函数:获取当前的时间和日期。
返回值:通过参数返回一个 timeb 结构体。

  • timeb 结构体定义:
struct timeb {
    time_t time;			/* 为1970-01-01至今的秒数*/
    unsigned short millitm; /* 千分之一秒即毫秒 */
    short timezone;  		/* 为时区和Greenwich相差的时间,单位为分钟 */
    short dstflag;   		/* 为日光节约时间的修正状态,如果为非0代表启用日光节约时间修正 */
};

(2)函数 struct tm *localtime(const time_t *clock);

头文件:#include <time.h>
函数说明:把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间。
返回值:指向 tm 结构体的指针。

  • tm 结构体定义:
struct tm {
  int tm_sec;			//秒[0-59]
  int tm_min;			//分[0-59]
  int tm_hour;			//时[0-23]
  int tm_mday;			//日[1-31]
  int tm_mon;			//月份[0-11],0代表一月
  int tm_year;			//年份,需要加上1900
  int tm_wday;			//星期[0-6],0代表星期天
  int tm_yday;			//从每年1月1日开始的天数[0-365],0代表1月1日
};

2.2、Windows下的相关函数

(1)函数 VOID GetSystemTime(LPSYSTEMTIME lpSystemTime);

头文件:#include <windows.h>
函数说明:获取当前系统日期和时间,是UTC时间。
返回值:通过参数返回 LPSYSTEMTIME 结构体指针。

  • LPSYSTEMTIME 结构体定义:
typedef struct _SYSTEMTIME {
    WORD wYear;           //年
    WORD wMonth;          //月[1-12]
    WORD wDayOfWeek;      //星期[0-6],0代表星期天
    WORD wDay;            //日[1-31]
    WORD wHour;           //时[0-23]
    WORD wMinute;         //分[0-59]
    WORD wSecond;         //秒[0-59]
    WORD wMilliseconds;   //毫秒[0-999]
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

(2)函数 struct tm *localtime(const time_t *clock);

与上述Linux下的描述相同。

2.3、代码实现

  头文件 dateTime.h

#ifndef DATETIME_H
#define DATETIME_H

#include <time.h>

//Windows系统时间结构体
//typedef struct _SYSTEMTIME {
//    WORD wYear;           //年
//    WORD wMonth;          //月[1-12]
//    WORD wDayOfWeek;      //星期[0-6],0代表星期天
//    WORD wDay;            //日[1-31]
//    WORD wHour;           //时[0-23]
//    WORD wMinute;         //分[0-59]
//    WORD wSecond;         //秒[0-59]
//    WORD wMilliseconds;   //毫秒[0-999]
//  } SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

//当前使用的系统环境
#define SYSTEM_ENVIRONMENT  0 //0:Linux     1:Windows

//日期时间信息结构体
struct dateTime {
    int year;		//年
    int mon;        //月[1-12]
    int mday;		//日[1-31]
    int hour;		//时[0-23]
    int min;		//分[0-59]
    int sec;		//秒[0-59]
    int msec;       //毫秒[0-999]
    int wday;		//星期[0-6],0代表星期天
    int yday;		//从每年1月1日开始的天数[0-365],0代表1月1日
};

//获取当前日期时间,精确到毫秒
int getCurrentDateTime(struct dateTime *now, char *str, const char *format);

#if !SYSTEM_ENVIRONMENT //Linux

//获取当前系统时间戳,精确到毫秒
unsigned long long getSystemTime_ms(void);
//获取当前系统时间戳,精确到微秒
unsigned long long getSystemTime_us(void);
//延时毫秒
void delay_ms(unsigned long long nms);
//延时微秒
void delay_us(unsigned long long nus);

#else //Windows

//获取系统时间
int getSystemTime(SYSTEMTIME *currentTime);

#endif

#endif // DATETIME_H

  源文件 dateTime.c

#include "dateTime.h"
#include <string.h>
#include <stdio.h>

#if !SYSTEM_ENVIRONMENT //Linux

#include <sys/timeb.h>
#include <sys/time.h>

#else //Windows

#include <windows.h>

#endif

//Linux日期时间结构体部分参数
//struct tm
//{
//  int tm_sec;			//秒[0-59]
//  int tm_min;			//分[0-59]
//  int tm_hour;		//时[0-23]
//  int tm_mday;		//日[1-31]
//  int tm_mon;			//月份[0-11],0代表一月
//  int tm_year;		//年份,需要加上1900
//  int tm_wday;		//星期[0-6],0代表星期天
//  int tm_yday;		//从每年1月1日开始的天数[0-365],0代表1月1日
//};

/**
 * @brief getCurrentDateTime    获取当前日期时间,精确到毫秒
 * @param now                   当前日期时间信息,不需要可传入NULL
 * @param str                   当前日期时间信息字符串输出,不需要可传入NULL
 * @param format                当前日期时间信息字符串输出格式,不需要可传入NULL
 * @return  int                 0:成功    -1:失败
 * 格式format:yyyy--年  MM--月  dd--日  hh--时  mm--分  ss--秒  zzz--毫秒
 * 示例:yyyyMMddhhmmsszzz、yyyy-MM-dd hh:mm:ss.zzz 等
 */
int getCurrentDateTime(struct dateTime *now, char *str, const char *format)
{
    unsigned short msec;
    char buf[24] = {0};
    char *p = NULL;
    struct tm *tm_now = NULL;
#if !SYSTEM_ENVIRONMENT //Linux
    struct timeb t;
    ftime(&t);
    msec = t.millitm;
    tm_now = localtime(&t.time);
#else //Windows
    time_t t;
    SYSTEMTIME currentTime;
    time(&t);
    GetSystemTime(&currentTime); //获取当前的UTC时间
    msec = currentTime.wMilliseconds;
    tm_now = localtime(&t);
#endif
    if(!tm_now) {
        return -1;
    }
    if(now) {
        now->year = tm_now->tm_year+1900;
        now->mon = tm_now->tm_mon+1;
        now->mday = tm_now->tm_mday;
        now->hour = tm_now->tm_hour;
        now->min = tm_now->tm_min;
        now->sec = tm_now->tm_sec;
        now->msec = msec;
        now->wday = tm_now->tm_wday;
        now->yday = tm_now->tm_yday;
    }
    if(str) {
        if(!format) {
            //默认格式:yyyyMMddhhmmsszzz
            sprintf(str, "%d%02d%02d%02d%02d%02d%03d", tm_now->tm_year+1900, tm_now->tm_mon+1,
                    tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, msec);
        }
        else {
            sprintf(buf, "%d%02d%02d%02d%02d%02d%03d", tm_now->tm_year+1900, tm_now->tm_mon+1,
                    tm_now->tm_mday, tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, msec);
            strcpy(str, format);
            if(p = strstr(str, "yyyy")) { strncpy(p, buf, 4); }
            if(p = strstr(str, "MM")) { strncpy(p, buf + 4, 2); }
            if(p = strstr(str, "dd")) { strncpy(p, buf + 6, 2); }
            if(p = strstr(str, "hh")) { strncpy(p, buf + 8, 2); }
            if(p = strstr(str, "mm")) { strncpy(p, buf + 10, 2); }
            if(p = strstr(str, "ss")) { strncpy(p, buf + 12, 2); }
            if(p = strstr(str, "zzz")) { strncpy(p, buf + 14, 3); }
        }
    }
    return 0;
}

#if !SYSTEM_ENVIRONMENT //Linux

/**
 * @brief getSystemTime_ms      获取当前系统时间戳,精确到毫秒
 * @param
 * @return  unsigned long long  获取到的时间戳
 */
unsigned long long getSystemTime_ms(void)
{
    struct timeb t;
    ftime(&t);
    return (1000*t.time + t.millitm);
}

/**
 * @brief getSystemTime_us      获取当前系统时间戳,精确到微秒
 * @param
 * @return  unsigned long long  获取到的时间戳
 */
unsigned long long getSystemTime_us(void)
{
    struct timeval t;
    gettimeofday(&t, NULL);
    return (1000000*t.tv_sec + t.tv_usec);
}

/**
 * @brief delay_ms  延时毫秒
 * @param nms       需要延时的毫秒数
 * @return
 */
void delay_ms(unsigned long long nms)
{
#if 0 //方法一
    unsigned long long start;
    start = getSystemTime_ms();
    while(getSystemTime_ms() - start < nms);
#else //方法二
    struct timeb start, end;
    ftime(&start);
    while(1) {
        ftime(&end);
        if(1000*(end.time - start.time) + end.millitm - start.millitm >= nms) {
            return;
        }
    }
#endif
}

/**
 * @brief delay_us  延时微秒
 * @param nus       需要延时的微秒数
 * @return
 */
void delay_us(unsigned long long nus)
{
#if 0 //方法一
    unsigned long long start;
    start = getSystemTime_us();
    while(getSystemTime_us() - start < nus);
#else  //方法二
    struct timeval start, end;
    gettimeofday(&start, NULL);
    while(1) {
        gettimeofday(&end, NULL);
        if(1000000*(end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec >= nus) {
            return;
        }
    }
#endif
}

#else //Windows

/**
 * @brief getSystemTime     获取系统时间
 * @param currentTime       获取到的系统时间,已从UTC时间转为北京时间
 * @return int              0:成功    -1:失败
 */
int getSystemTime(SYSTEMTIME *currentTime)
{
    if(!currentTime) {
        return -1;
    }
    GetSystemTime(currentTime); //获取当前的UTC时间
    currentTime.wHour += 8; //中国北京时间比UTC时间早8小时,第八时区
    return 0;
}

#endif

附:源代码下载

C语言获取当前日期和时间.zip

  • 3
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶落花枯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值