我在 stackoverflow 网站上查看了我的答案,我没有得到,所以我把它贴在这里.
I checked the stackoverflow site for my answer, i did not get, so i am posting it here.
我的问题是:
如何比较格式"Month Date hh:mm:ss"
的两个时间戳?
How to compare two time stamp in format
"Month Date hh:mm:ss"
?
我正在用 C 和 C++ 编写程序,时间是可显示的字符串格式.
I am writing program in C and C++ and the time is in displayable string format.
示例:
time1 = "Mar 21 11:51:20"
time2 = "Mar 21 10:20:05"
我想比较 time1 和 tme2 并找出 time2
是否是 after time1
并且我需要输出为 true
或 false
,如下所示:
I want to compare time1 and tme2 and find out whether time2
is after time1
or not and I need output as true
or false
, like below:
if time2 > time1 then
i need output as 1
or
0 or -1 anything
我使用了 difftime(time2,time1)
,但它返回 time1
和 time2
之间的增量时间 diff
>.
我想检查是否更大.
I used difftime(time2,time1)
, but it returns the delta time diff
between time1
and time2
.
I want to check greater or not.
如有任何帮助,提前致谢
For any help, thanks in advance
FIRST-使用difftime进行比较:
FIRST- use difftime to compare:
你可以简单地使用 difftime()
比较时间并返回1
或-1
的函数如下:
you can simply use difftime()
function to compare time and return 1
or -1
as follows:
int comparetime(time_t time1,time_t time2){
return difftime(time1,time2) > 0.0 ? 1 : -1;
}
SECOND- 将字符串转换为时间:
SECOND- Convert string into time:
如果你转换 string
转化为 time_t
结构有困难,你可以依次使用两个函数:
If you have difficulty to convert string
into time_t
struct, you can use two functions in sequence:
char *strptime(const char *buf, const char *format, struct tm *tm);
函数.将字符串转换为 struct tm
示例:将日期时间字符串 "Mar 21 11:51:20 AM"
转换为 struct tm
您需要三个格式化字符串:
Example: to convert date-time string "Mar 21 11:51:20 AM"
into struct tm
you need three formate strings:
%b :月份名称,可以是全名或缩写
%d:月中的第几天 [1–31].
%r :区域设置的 AM/PM 格式的时间.如果在本地时间格式中不可用,则默认为 POSIX 时间 AM/PM 格式:%I:%M:%S %p
.
%b : Month name, can be either the full name or an abbreviation
%d : Day of the month [1–31].
%r : Time in AM/PM format of the locale. If not available in the locale time format, defaults to the POSIX time AM/PM format:%I:%M:%S %p
.
time_t mktime (struct tm * timeptr);
函数将 struct tm*
转换为 time_t
下面是我的示例程序:
#include <stdio.h>
#include <time.h>
int main(void){
time_t t1, t2;
struct tm *timeptr,tm1, tm2;
char* time1 = "Mar 21 11:51:20 AM";
char* time2 = "Mar 21 10:20:05 AM";
//(1) convert `String to tm`:
if(strptime(time1, "%b %d %r",&tm1) == NULL)
printf("
strptime failed
");
if(strptime(time2, "%b %d %r",&tm2) == NULL)
printf("
strptime failed
");
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
t2 = mktime(&tm2);
printf("
t1 > t2 : %d", comparetime(t1, t2));
printf("
t2 > t1 : %d", comparetime(t2, t1));
printf("
");
return 1;
}
它如你所愿:
$ ./a.out
t1 > t2 : 1
t2 > t1 : -1
要计算两个日期之间的差异,请阅读:在 C 中,您如何以小时为单位找到两个日期之间的差异?
To calculate difference between two dates read: How do you find the difference between two dates in hours, in C?
这篇关于如何以“月份日期 hh:mm:ss"格式比较两个时间戳检查 +ve 或 -ve 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!