0

I want to convert from specific date to seconds in C. For example, If I give 12/25/2015, it will convert into seconds. This is the program I found to convert current date to seconds. But I want to convert from specific date to seconds.

time_t timer;
  struct tm y2k;
  double seconds;

  y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
  y2k.tm_year = 0; y2k.tm_mon = 0; y2k.tm_mday = 1;

  time(&timer);  

  seconds = difftime(timer,mktime(&y2k));

  printf ("%.f ", seconds); 
Manu343726
  • 13,969
  • 4
  • 40
  • 75
Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75

3 Answers3

0

The result of mktime() is the number of seconds (give or take a few leap seconds) since midnight 1970-01-01 00:00:00 UTC.

This is also know as Unix time.

pmg
  • 106,608
  • 13
  • 126
  • 198
0

Read the man page on the tm structure (http://www.cplusplus.com/reference/ctime/tm/). For 25 Dec 2015,

y2k.tm_year = 2015 - 1900; /* Starts from 1900 */
y2k.tm_mon = 12 - 1; /* Jan = 0 */
y2k.tm_mday = 15;

Also, to print a double, use %lf. You may not get the result you want if you just use %f.

cup
  • 7,589
  • 4
  • 19
  • 42
  • 2
    `"%f"` or "`%lf`" have exactly the same meaning in `printf()`, since C99 (they differ in `scanf()`). – pmg Mar 15 '14 at 14:16
0

You might also find strptime(3) useful.

#include <stdio.h>
#include <string.h>
#include <time.h>

int
main(int ac, char *av[])
{
    char format[] = "%m/%d/%y";
    char input[] = "12/25/15";
    char buf[256];
    struct tm tm;

    memset(&tm, 0, sizeof tm);

    if (strptime(input, format, &tm) == NULL) {
         fputs("strptime failed\n", stderr);
         return 1;
    }

    strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);

    printf("reformatted: %s; as time_t: %ld\n", buf, mktime(&tm));

    return 0;
}
sjnarv
  • 2,334
  • 16
  • 13