如何比较两个时间标记的格式和QUOT;当月日期hh:mm:ss的"检查+ ve或-ve值 [英] How to compare two time stamp in format "Month Date hh:mm:ss" to check +ve or -ve value
问题描述
我检查我的回答对计算器的网站,我没有得到,所以我在这里张贴。
I checked the stackoverflow site for my answer, i did not get, so i am posting it here.
我的问题是:
如何比较格式两个时间戳记月日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"
我想比较时间1和tme2并找出时间2
是的之后的时间1
与否,我需要为输出真正
或假
,象下面这样:
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(时间2,时间1)
,但它返回的时间增量差异
<$ C $之间C>时间1 和时间2
。结果
我要检查更大与否。
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;
}
第二 - 转换成字符串时间:
如果您有困难的转换 字符串
到 time_t的
结构,可以按顺序使用两个功能:
If you have difficulty to convert string
into time_t
struct, you can use two functions in sequence:
例如:转换时间串3月21日上午十一时51分20秒
到结构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(结构TM * timeptr);
功能转换结构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("\nstrptime failed\n");
if(strptime(time2, "%b %d %r",&tm2) == NULL)
printf("\nstrptime failed\n");
//(2) convert `tm to time_t`:
t1 = mktime(&tm1);
t2 = mktime(&tm2);
printf("\n t1 > t2 : %d", comparetime(t1, t2));
printf("\n t2 > t1 : %d", comparetime(t2, t1));
printf("\n");
return 1;
}
和它的作品,你的愿望:
And it works as you desire:
$ ./a.out
t1 > t2 : 1
t2 > t1 : -1
要计算两个日期之间的区别如下:<一href=\"http://stackoverflow.com/questions/21862808/how-do-you-find-the-difference-between-two-dates-in-hours-in-c/21864664#21864664\">How你觉得以小时为单位的两个日期之间的差别,在C?
To calculate difference between two dates read: How do you find the difference between two dates in hours, in C?
这篇关于如何比较两个时间标记的格式和QUOT;当月日期hh:mm:ss的&QUOT;检查+ ve或-ve值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!