字符串转换:
long int strtol(char const *string, char **unused, int base);
将字符串转换为数值形式,遇到非法字符停止,如果stop不是NULL,则将转换停止位置储存在stop中。
#include <stdlib.h> #include <stdio.h> int main() { //stop储存转换停止的位置的指针 char *stop; printf("%ld ", strtol("123abc", &stop, 10)); printf("%s ", stop); //如果字符串以0x开头,base为0或者16都会以16进制转换 printf("%ld ", strtol("0x123", &stop, 16)); printf("%s ", stop); printf("%ld ", strtol("0x123", &stop, 0)); printf("%s ", stop); //当base不是0和16遇到0x,为非法字符 printf("%ld ", strtol("0x123", &stop, 10)); printf("%s ", stop); return 0; }
运行:
日期和时间:
clock_t clock(void);
clock返回从秩序开始执行处理器所消耗的时间,通常是处理器时钟的滴答次数,如果需要转换成秒,需要除以常量 CLOCKS_PER_SEC
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <windows.h> int main() { clock_t start; clock_t end; //开始时间 start = clock(); //睡眠3000毫秒 Sleep(3000); //结束时间 end = clock(); printf("%lu", (end - start) / CLOCKS_PER_SEC); return 0; }
运行:
time_t time(time_t *returned_value);
不同编译器有不同返回值,所以不可以通过两次相减获得时间差,一般默认返回从1970后到现在的秒数,如果需要时间差可以通过difftime函数
int main() { time_t now; now = time(NULL); printf("%lu", now); return 0; }
运行:
char *ctime(time_t const *time_value)
ctime函数的参数是一个指向time_t的指针,并返回一个指向字符串的指针
struct tm *gmtime(time_t const *time_value) struct tm *localtime(time_t const *time_value)
gmtime函数把时间值转换为世界协调时间,localtime转换为本地时间,struct tm结构包含时间的各个字段信息。
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <windows.h> int main() { time_t now; time_t end; char *time_s; //now为1970年至今时间戳 now = time(NULL); //time_s为日期字符串格式 time_s = ctime(&now); printf("%s %lu ", time_s, now); //休眠一秒 Sleep(1000); end = time(NULL); //difftime返回秒数时间差 printf("between %g ", difftime(end, now)); //localtime转换time_t值为tm结构,tm结构包含日期和时间的各个组成部分 struct tm *tm_time = localtime( &end); //tm结构体中月份以0为开始, tm_year以1900为起始年 printf("%d %d %d ", tm_time -> tm_mon + 1, tm_time -> tm_mday, tm_time -> tm_year + 1900); //gmtime转换为UTC时间 tm_time = gmtime( &end); //tm结构体中月份以0为开始, tm_year以1900为起始年 printf("%d %d %d ", tm_time -> tm_mon + 1, tm_time -> tm_mday, tm_time -> tm_year + 1900); //asctime函数把tm参数所表示的时间转换为一个指定格式的字符串 char *astime; astime = asctime(tm_time); printf("%s ", astime); return 0; }
运行:
函数strftime把一个tm结构转换成一个根据某个格式字符串而指定的字符串。
size_t strftime(char *string, size_t maxsize, char const *format, struct tm const *tm_ptr);
如果转换结果字符串长度小于maxsize参数,那么该字符串就被复制到第一个参数指定的数组中。
#include <stdlib.h> #include <stdio.h> #include <time.h> int main() { char format_time[100]; size_t maxsize = 100; char format[100] = "%Y-%m-%d %H:%M:%S"; time_t now; now = time(NULL); struct tm *time_tm = localtime(&now); strftime(format_time, maxsize, format, time_tm); printf("%s", format_time); return 0; }
运行:
localtime和gmtime可以把time_t转换成tm结构体个,而mktime可以把tm结构体转换成time_t值
time_t mktime(struct tm *tm_ptr)