[英]Convert time_t To Integer
如何修改此代碼每隔00:00 AM打印一次(“午夜”)?
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm * localtime ( const time_t * ptr_time );
struct tm
{
int tm_sec; /* segundos, range 0 to 59 */
int tm_min; /* minutos, range 0 to 59 */
int tm_hour; /* horas, range 0 to 23 */
int tm_mday; /* dia do mes, range 1 to 31 */
int tm_mon; /* mes, range 0 to 11 */
int tm_year; /* numero de anos desde 1900 */
int tm_wday; /* dia da semana, range 0 to 6 */
int tm_yday; /* dia no ano, range 0 to 365 */
int tm_isdst;
};
time_t mytime;
mytime = time(NULL);
printf(ctime(&mytime));
/*
if(str_time.tm_hour == 00 && str_time.tm_min == 00 && str_time.tm_sec == 00 )
{
printf("Its midnight");
}
*/
return 0;
}
time_t的輸出為:Www Mmm dd hh:mm:ss yyyy
示例:Tue Feb 26 09:01:47 2009
通常,time_t實現為32或64位整數。 雖然,沒有標准來定義這個。 所以,如果你擔心可移植性,你可能不應該使用它。 但是,如果您不是,那么您應該測試它在您的系統上的實現方式。 它可能已被視為整數。
編輯:如果你試圖打破time_t的一些元素,那么使用像,
struct tm * localtime ( const time_t * ptr_time );
返回的tm結構看起來像這樣,
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
編輯2:
這個例子來自gnu.org 。 我拿出了印刷品,因為你不想使用它們,但我讓剩下的讓你弄明白了。
#include <time.h>
#include <stdio.h>
int
main (void)
{
time_t curtime;
struct tm *loctime;
/* Get the current time. */
curtime = time (NULL);
/* Convert it to local time representation. */
loctime = localtime (&curtime);
return 0;
}
如果能夠,請使用sleep()
暫停。
使用time()
和localtime()
來確定午睡時間。
#include <unistd.h>
#include <time.h>
#include <stdio.h>
int main() {
while (1) {
time_t Now;
if (time(&Now) == -1) {
return -1;
}
struct tm tm;
tm = *localtime(&Now);
tm.tm_mday++;
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_isdst = -1;
time_t Then;
Then = mktime(&tm);
if (Then == -1) {
return -1;
}
if (Then <= Now) {
return -1; // Time moving backwards - Hmmmm?
}
unsigned int NapTime = (unsigned int) (Then - Now);
printf("Going to sleep %u\n", NapTime );
fflush(stdout); // Let's empty the buffers before nap time
if (0 != sleep(NapTime)) {
return -1; // trouble sleeping
}
// Done sleeping!
printf("Midnight\n");
fflush(stdout);
sleep(10);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.