Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time_t To Integer

How should I modify this code to print("Its Midnight") every 00:00AM ?

#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;
}

The Output of time_t is: Www Mmm dd hh:mm:ss yyyy

Example: Tue Feb 26 09:01:47 2009

like image 313
Neto Avatar asked May 20 '26 18:05

Neto


1 Answers

If able, use sleep() to pause.
Use time() and localtime() to determine nap time.

#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);
    }
  }
like image 115
chux - Reinstate Monica Avatar answered May 22 '26 10:05

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!