1、strftime
函数的功能是把一个tm结构的时间序列化为一个字符串
#include <time.h>
size_t strftime(char *s, size_t max, const char *format,
const struct tm *tm);
参数:
char *s: 字符串指针 输出
size_t max: 字符串最大长度 输入
const char *format: 输出格式
const struct tm *tm: 时间 输入
返回值:
成功:处理结果字符串str中字符的个数
失败:0
格式如下:
%a 星期几的简写
%A 星期几的全称
%b 月份的简写
%B 月份的全称
%c 标准的日期的时间串
%C 年份的前两位数字
%d 十进制表示的每月的第几天
%D 月/天/年
%e 在两字符域中,十进制表示的每月的第几天
%F 年-月-日
%g 年份的后两位数字,使用基于周的年
%G 年份,使用基于周的年
%h 简写的月份名
%H
24小时制的小时
%I 12小时制的小时
%j 十进制表示的每年的第几天
%m 十进制表示的月份
%M 十时制表示的分钟数
%n 新行符
%p 本地的AM或PM的等价显示
%r 12小时的时间
%R 显示小时和分钟:hh:mm
%S 十进制的秒数
%t 水平
制表符
%T 显示时分秒:hh:mm:ss
%u 每周的第几天,星期一为第一天 (值从1到7,星期一为1)
%U 第年的第几周,把星期日作为第一天(值从0到53)
%V 每年的第几周,使用基于周的年
%w 十进制表示的星期几(值从0到6,星期天为0)
%W 每年的第几周,把星期一做为第一天(值从0到53)
%x 标准的日期串
%X 标准的时间串
%y 不带世纪的十进制年份(值从0到99)
%Y 带世纪部分的十制年份
%z,%Z 时区名称,如果不能得到时区名称则返回空字符。
%%
百分号
2、strptime
函数的功能是把一个字符串序列化为一个tm结构的时间
#define _XOPEN_SOURCE /* glibc2 needs this */
#include <time.h>
char *strptime(const char *s, const char *format, struct tm *tm);
参数:
const char *s: 字符串 输入
const char *format: 输入的格式
tm: 时间 输出
返回值:
成功:*s的最后位置
失败:NULL
3、stime
设置本地系统时间
#include <time.h>
int stime(time_t *t);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
stime(): _SVID_SOURCE
参数:
t: 日历时间 输入
返回值:
成功: 0
失败:-1
4、代码示例
设置本地系统时间
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
void SyncDateTime(const char *time)
{
struct tm temp;
printf("need to syncDateTime: %s\n", time);
if (strptime(time, "%Y-%m-%d %H:%M:%S", &temp) == NULL)
{
perror("strptime failed.\n");
}
time_t t = mktime(&temp);
if (stime(&t) == -1)
{
perror("stime failed.\n");
}
return ;
}
int main()
{
const char buf[] = "2015-03-05 10:11:50";
SyncDateTime(buf);
return 0;
}