Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Для новичков > помогите с time()


Автор: yngwie19 19.8.2008, 19:45
как с помощью функции time(), описанной в time.h получить текущее время. В книгах по С++ написано, что эта функция возвращает кол-во пройденых секунд  с 01.01.1970 по системную дату на момент вызова функции. А как его рассчитать на нужное?

Автор: MAKCim 19.8.2008, 19:54
Код

time_t t = time();
struct tm * tm = localtime(&t);

Автор: yngwie19 19.8.2008, 20:08
Что-то не получается много ошибок выдает, а по другому нельзя?

Автор: MAKCim 19.8.2008, 20:13
yngwie19
что за ошибки?

Автор: yngwie19 19.8.2008, 20:46
error C2660: 'time' : function does not take 0 parameters

Автор: IKM2007 19.8.2008, 21:06
Цитата(yngwie19 @  19.8.2008,  20:46 Найти цитируемый пост)
error C2660: 'time' : function does not take 0 parameters


Код

#include <iostream>
#include <ctime>
using namespace std;
void main()
{
time_t t = time(NULL);
struct tm * tm = localtime(&t);
cout<<asctime(tm)<<endl;
}

Автор: yngwie19 19.8.2008, 22:06
последний вопрос. А можно ли это время в секунды перевести?

Автор: IKM2007 19.8.2008, 22:37
Цитата(yngwie19 @  19.8.2008,  22:06 Найти цитируемый пост)
последний вопрос. А можно ли это время в секунды перевести?

То есть начиная с  01.01.1970г.?
Если да, то
Код

#include <iostream>
#include <ctime>
using std::cout;
using std::endl;
void main()
{
time_t t = time(NULL);
cout<<t<<endl;
}

Автор: MastEdm 19.8.2008, 23:29
Код

STRFTIME(3)                                               Linux Programmer's Manual                                               STRFTIME(3)

NAME
       strftime - format date and time

SYNOPSIS
       #include <time.h>

       size_t strftime(char *s, size_t max, const char *format,
                       const struct tm *tm);

DESCRIPTION
       The  strftime()  function  formats  the  broken-down time tm according to the format specification format and places the result in the
       character array s of size max.

       Ordinary characters placed in the format string are copied to s without conversion.  Conversion specifications are introduced by a '%'
       character, and terminated by a conversion specifier character, and are replaced in s as follows:

       %a     The abbreviated weekday name according to the current locale.

       %A     The full weekday name according to the current locale.

       %b     The abbreviated month name according to the current locale.

       %B     The full month name according to the current locale.

       %c     The preferred date and time representation for the current locale.

       %C     The century number (year/100) as a 2-digit integer. (SU)

       %d     The day of the month as a decimal number (range 01 to 31).

       %D     Equivalent to %m/%d/%y.  (Yecch — for Americans only.  Americans should note that in other countries %d/%m/%y is rather common.
              This means that in international context this format is ambiguous and should not be used.) (SU)

       %e     Like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (SU)

       %E     Modifier: use alternative format, see below. (SU)

       %F     Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)

       %G     The ISO 8601 year with century as a decimal number.  The 4-digit year corresponding to the ISO week number (see %V).  This  has
              the  same  format  and  value as %y, except that if the ISO week number belongs to the previous or next year, that year is used
              instead. (TZ)

       %g     Like %G, but without century, that is, with a 2-digit year (00-99). (TZ)

       %h     Equivalent to %b.  (SU)
....


В мане много про это написано, даже с примерами  smile 

Автор: taiven 20.8.2008, 04:24
Код

#include <cstdlib>
#include <iostream>
#include <ctime>

using namespace std;

int main(int argc, char *argv[])
{
     time_t tm;
     int hour, min, sec;
     char *end[1];
     char h[5], m[5], s[5];

     time(&tm);
     strftime(h, 3, "%H", localtime(&tm));
     strftime(m, 3, "%M", localtime(&tm));
     strftime(s, 3, "%S", localtime(&tm));

     hour = strtol(h, end, 10);
     min  = strtol(m, end, 10);
     sec = strtol(s, end, 10);

     cout << hour << '\n'
          << min << '\n'
          << sec << '\n';

     cout << "in sec: " << (hour * 3600) + (min * 60) + sec << '\n';


     system("PAUSE");
     return EXIT_SUCCESS;
}


Автор: W4FhLF 20.8.2008, 08:42
Можно воспользоваться boost::date_time. Огромные возможности. 

Небольшой пример:

Код

#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>

int main(int argc, char* argv[])
{
    using namespace boost::posix_time;
    ptime time(microsec_clock::local_time());

    std::cout << time << std::endl;                    // Дата и время целиком
    std::cout << time.time_of_day() << std::endl;    // Только время
    std::cout << time.date() << std::endl;            // Только дата

    return 0;
}

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)