time_t

The most basic representation of a date and time is the type time_t. The value of a time_t variable is the number of seconds since January 1, 1970, sometimes call the Unix epoch. This is the best way to internally represent the start and end times for an event because it is easy to compare these values. Two time_t values a and b can be compared using <:

if(a < b)
{
printf("Time a is before time b\n");
}
struct tm

While time_t represents a date and time as a single number, struct tm represents it as a struct with a lot of numbers:

struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
};
Conversion

You can convert a time_t value to a struct tm value using the localtime function:

struct tm startTM;
time_t start; /* ... */ startTM = *localtime(&start);

You can convert a struct tm value to a time_t value using the mktime function:

struct tm startTM;
time_t start; /* ... */ start = mktime(&startTM);
How to input a date

Your program will need to input a date. Here is an example of a safe and robust way to input a date:

time_t InputDate(char *prompt)
{
char buffer[100];
char *result;
struct tm date; do
{
printf("%s", prompt); /* Get a line of up to 100 characters */
fgets(buffer, sizeof(buffer), stdin); /* Remove any \n we may have input */
if(strlen(buffer) > 0)
buffer[strlen(buffer)-1] = '\0'; result = strptime(buffer, "%m/%d/%Y", &date); } while(result == NULL); /* Convert to time_t format */
date.tm_min = 0;
date.tm_hour = 0;
date.tm_sec = 0;
date.tm_isdst = 1; return mktime(&date);
}

This function asks the user for a time with the given prompt. If the time is correctly entered, it converts it to type time_t, expressing a time and date of 12:00am on the entered date.

In order to use the strptime function, you will need to #include <time.h>. However, you must preceed the #include with this code:

#define __USE_XOPEN
#include <time.h>

Any time you #include <time.h> in your program, use the line #define __USE_XOPEN before it. Note that it begins with two underlines.

How to input a time

After entering the date, you can enter a time using this safe and robust function:

time_t InputTime(char *prompt, time_t date)
{
char buffer[100];
char *result;
struct tm time; time = *localtime(&date); do
{
printf("%s", prompt); /* Get a line of up to 100 characters */
fgets(buffer, sizeof(buffer), stdin); /* Remove any \n we may have input */
if(strlen(buffer) > 0)
buffer[strlen(buffer)-1] = '\0'; result = strptime(buffer, "%I:%M%p", &time); } while(result == NULL); return mktime(&time);
}

This function is passed a date expressed as a time_t value, the output of the InputDate function. The time is entered and added to the date to produce a date and time value that is returned. Here is an example of how these functions can be used to input a date, start time, and end time.

time_t date;
time_t start;
time_t end; /*...*/ date = InputDate("Event date: ");
start = InputTime("Start time: ", date);
end = InputTime("End time: ", date);
How to output a time_t value.

To output a time or date, you convert it to a struct tm:

struct tm startTM;
time_t start; /* ... */ startTM = *localtime(&start);

Once converted, the value in struct tm are:

struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
};

Now I can get the hour in the example as startTM.tm_hour. There are a couple strange things about this struct. To get the actual year, use startTM.tm_year + 1900.  To get the actual month number, use startTM.tm_mon + 1.

The function ctime

The function ctime converts a time_t value into a string of the following form:

Thu Apr 14 14:00:00 2011

This is a handy way to test to see if a time is what you expect. For example, if I have a variable: time_t timeDate and want to know what its value is, I can add this code while debugging:

printf("The date/time is %s\n", ctime(&timeDate));

This is also the easiest way to save the start date/time and end date/time to a file.

Reading the output of ctime

To read the output of ctime from a file and convert it back to a time_t value, use this code:

struct tm tim;
time_t startTime; fgets(buffer, sizeof(buffer), file);
strptime(buffer, "%a %b %d %H:%M:%S %Y", &tim);
startTime = mktime(&tim);

This inputs the date/time string from a file into the character string buffer. It then used strptime to convert it to a struct tm structure. Then the funciton mktime converts the struct tm value to a time_t value.

c 语言时间的输出和比较的更多相关文章

  1. YTU 2416: C语言习题 成绩输出

    2416: C语言习题 成绩输出 时间限制: 1 Sec  内存限制: 128 MB 提交: 1111  解决: 417 题目描述 输入n(<=10)个学生的姓名.学号和成绩,将其中不及格者的姓 ...

  2. C 语言 时间函数使用技巧(汇总)

    time.h 头文件 是 C 语言中 有关 时间的函数所储存的头文件 #include <time.h> 在介绍时间函数用法之前,我们首先要了解在 time.h 头文件中已经声明了的一个结 ...

  3. ls按时间排序输出文件列表

    文件转自:http://www.2cto.com/os/201303/197829.html ls按时间排序输出文件列表   首先,ls --help查看ls相关的与时间排序相关的参数:   > ...

  4. [转]C语言文件输入/输出ACM改进版(freopen函数)

    C语言文件输入/输出ACM改进版(freopen函数) 2009年5月27日 10:379,457 浏览数发表评论阅读评论   文章作者:姜南(Slyar) 文章来源:Slyar Home (www. ...

  5. C语言中格式化输出的转换说明的fldwidth和precision解析

    首先说什么是C语言的格式化输出,就是printf和它的几个变种(grep -E "v?(sn|s|f)printf").像这些函数都有一个参数format,format中可以加点转 ...

  6. Python中日期和时间格式化输出的方法

    本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...

  7. C 语言实例 - 循环输出26个字母

    C 语言实例 - 循环输出26个字母 循环输出 个字母. 实例 #include <stdio.h> int main() { char c; for(c = 'A'; c <= ' ...

  8. go语言时间函数

    以YY-mm-dd HH:MM:SS.9位 输出当前时间: func main() { fmt.Println(time.Now()) // 2019-11-15 16:26:12.4807588 + ...

  9. C语言 · 时间转换

    问题描述 给定一个以秒为单位的时间t,要求用"<H>:<M>:<S>"的格式来表示这个时间.<H>表示时间,<M>表示分 ...

随机推荐

  1. 大话设计模式C++实现-第22章-桥接模式

    一.UML图 二.概念 桥接模式(Bridge):将抽象部分与它的实现部分分离,使他们都能够独立地变化. 三.说明 为什么叫"桥接模式"? 如上所看到的的UML图中,有一个聚合线, ...

  2. 使用贝赛尔曲线画扇形、圆形、弧线、多边形,实现App下载时的动画效果demo

    // // MyView.swift // TestUIBezierPath // // Created by iCodeWoods on 16/5/8. // Copyright © 2016年 i ...

  3. Network Link Conditioner模拟不同网络环境

    在Xcode4.1中有一个工具叫Network Link Conditioner,可以让用户模拟不同的网络连接和带宽,可供Mac和iOS开发者测试自己的程序在不同网络环境下的表现. 在Xcode4.3 ...

  4. 对lua继承中self.__index = self的释疑

    首先看看从lua表中查找一个键时的流程: -- 当从表t中查找键k时,lua处理如下: -- 1.t中是否有k,有则直接返回值,否则第2步 -- 2.t是否有元表, 无则返回nil, 有则第3步 -- ...

  5. 内存映射mmap

    Table of Contents 1. 什么是mmap 2. 使用方法 2.1. mmap构造器的格式 2.2. 例子1 2.3. 例子2 3. 其它 4. 参考资料 什么是mmap 通常在Unix ...

  6. python编码encode和decode

    计算机里面,编码方法有很多种,英文的一般用ascii,而中文有unicode,utf-8,gbk,utf-16等等. unicode是 utf-8,gbk,utf-16这些的父编码,这些子编码都能转换 ...

  7. hadoop2 作业执行过程之reduce过程

    reduce阶段就是处理map的输出数据,大部分过程和map差不多 //ReduceTask.run方法开始和MapTask类似,包括initialize()初始化,根据情况看是否调用runJobCl ...

  8. Load Balancing 折半枚举大法好啊

    Load Balancing 给出每个学生的学分.   将学生按学分分成四组,使得sigma (sumi-n/4)最小.         算法:   折半枚举 #include <iostrea ...

  9. JavaScript组成

    JavaScript由ECMAScript,Dom,Bom三部分组成. ECMAScript是一种由Ecma国际(前身为欧洲计算机制造商协会,英文名称是European Computer Manufa ...

  10. [经典算法] 排列组合-N元素集合的M元素子集

    题目说明: 假设有个集合拥有n个元素,任意的从集合中取出m个元素,则这m个元素所形成的可能子集有那些? 题目解析: 假设有5个元素的集合,取出3个元素的可能子集如下: {1 2 3}.{1 2 4 } ...