1
#include "stdafx.h"
#include <iostream>
#include <ctime>


using namespace std;
int main()
{

time_t now = time(NULL);

int sec = now % 60;

int min = ((now - sec) / 60) % 60;

int hour = ((((now - sec) / 60) - min) / 60) % 24;

int day = ((((((now - sec) / 60) - min) / 60) - hour) / 24) % 30;

int month = ((((((((now - sec) / 60) - min) / 60) - hour) / 24) - day) / 30) % 12;

int year = ((((((((((now - sec) / 60) - min) / 60) - hour) / 24) - day) / 30) - month) / 12) + 1970;

cout << hour << ":" << min << ":"<< ":" << day << ":" << month << ":" << year<<endl;
}

I can't understand why month output 10 instead of 3 ???

(I know there is c_time function but i am learning and making my own one)

3 Answers3

1

time() function returns a number of seconds since January 1st, 1970.

Converting this into a date is much more complex than you think:

  • It starts with calculating the seconds: taking the number %60 should in principle tell the seconds in the current minute. That seems obvious. But this is not exact: it doesn't take into account the 25 leap seconds that took place since 1970.
  • minutes, hours would be ok if you take into account this first correction (and eventually taking into account daylight saving time, if this code is not ran in winter)
  • your calculation of the day of the month does not take into account the fact that not all the months are 30 days long, and it doesn't take into account the leap years.
  • And basically, the calculation of the months and the year would be affected by the impact of the wrong estimation of month.

Do yourself a favour and convert the date using a standard function like gmtime() or localtime() and accessing the fields of the struct tm

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

It is extremely daunting task of converting 'seconds since epoch' to day/month/year/etc.

This is why library got you covered. There are gmtime_r() and localtime()_r designed specifically for that. Unfortunately, those functions are not standard, and the only standard ones are thread unsafe gmtime() and localtime().

SergeyA
  • 61,605
  • 5
  • 78
  • 137
0

Converting seconds to days/hours/minutes is trivial. Converting days since 1970 to current date is not. You either should use library functions if you can or you may use formula provided for Julian day, just pay attention that 1/1/1970 is not 0 for Julian day.

PS subtracting reminder is completely unnecessary:

int min = ((now - sec) / 60) % 60;

should be:

int min = now / 60 % 60;

or even better:

int sec = now % 60;
now /= 60;
int min = now % 60;
now /= 60;

and so on.

Slava
  • 43,454
  • 1
  • 47
  • 90