ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

时间和日期例程(个人理解的笔记)

2021-09-23 10:02:37  阅读:200  来源: 互联网

标签:00 struct 例程 笔记 int 日期 tm 时间 time


废话不说那么多咱们先上个图

什么是时间戳,为什么会有时间戳?

时间戳就是Unix时间戳(Unix timestamp),定义为从格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。然后时间戳是不会跟着时区的改变而改变,所以不管你在哪个时区,时间戳都是一致的。这样我们就避免了重复修改数据所带来的错误。

下面是几个常用的时间结构转换函数

time()

 

头文件:

#include <time.h>

函数原型:

time_t time(time_t *tloc);

int main()
{
        time_t temp;
        int s = time(&temp);
        printf("%d\n",s);
​
}
stamp = time(NULL);

int s = time(NULL);
printf("%d\n",s);

 功 能: 获取当前的系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示从CUT(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。然后调用localtime将time_t所表示的CUT时间转换为本地时间(我们是+8区,比CUT多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。

返回值:返回一个长整形的时间戳,失败则返回((time_t)-1)值,错误原因存于errno 中。

localtime()

函数原型:

struct tm *localtime(const time_t *timep);

描述/返回值:将timep转换为一个结构体类型struct tm,以结构体指针的形式返回

struct tm的定义

struct tm {
    int tm_sec;    /* Seconds (0-60) */
    int tm_min;    /* Minutes (0-59) */
    int tm_hour;   /* Hours (0-23) */
    int tm_mday;   /* Day of the month (1-31) */
    int tm_mon;    /* Month (0-11) */
    int tm_year;   /* Year - 1900 */
    int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
    int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
    int tm_isdst;  /* Daylight saving time *
    };

mktime()

time_t mktime(struct tm *tm);

描述:将结构体tm转换为一个长整形的时间戳

返回值:成功返回结构体,失败返回-1

注:在转换之前会先进性校验并改变结构体tm使tm合法。

On success, mktime() returns the calendar time  (seconds since the Epoch), expressed as a value of type time_t.//成功返回 time_t类型的结构体
​
On  error,  mktime() returns the value (time_t) -1.  错误返回-1
The remaining functions return NULL  on  error.   On  error,errno is set to indicate the cause of the error.
会修改整理你的格式
​

strftime()

strftime() 函数根据区域设置格式化本地时间/日期,函数的功能将时间格式化,或者说格式化一个时间字符串。

size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);

strftime() 将tm结构体中的数据转换为字符型并按格式存储在s中

以下是常用的几个参数以及含义:

参数:
​
s:存储存储时间的字符串
​
max:要写入的最大字符
​
format:格式
​
tm:时间戳
常用的几种:
​
%Y:四位数的年
​
%m:月
​
%d:日
​
%M:分
​
%S:秒
​
​

标签:00,struct,例程,笔记,int,日期,tm,时间,time
来源: https://blog.csdn.net/qq_44934156/article/details/120421554

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有