time 함수를 사용한 프로그램에서 질문 ;ㅁ;

teshi의 이미지

타임 함수를 사용해서 하나의 프로그램을 짰습니다.

그 프로그램이란 것이... 이번년도 초 부터 지금까지 지난 시간을 일, 시간, 분, 초로 표시하는 거였습니다.

그래서 1970 년 1월 1일 부터 2007년도 1월 1일까지의 초를 구해서 현재 초에서 빼는 것이었습니다.

그렇게 해서...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
int main(void)
{
   time_t t;
   struct tm *local;
   int i;
   	int year;
   	int fly_sec;
   	int result_sec, result_min, result_hour, result_day;
   	int sec_check;
   	int check_plus_day = 0;
 
   	printf("현재 년도를 입력하세요 _ ");
   	scanf("%d", &year);
   	fflush(stdin);
        //윤년 평년 구하는 부분.
   	for(i = 1970; i < year ; i++)
   	{       
      		if((i % 4) == 0 &&  (( i% 100) != 0) || ((i % 400) == 0))
   	   	{
   	   		check_plus_day = check_plus_day + 366;
	   	}
   	   	else
   	   	{
   	   		check_plus_day = check_plus_day + 365;
   	   	}
   	}
 
 
           //초로 변환
   	sec_check = check_plus_day * 24 * 60 * 60;
 
   	t = time(NULL);
 
           //전체 초에서 당해 년도 까지의 초를 뺌
   	fly_sec = t - sec_check;
 
   	result_sec = fly_sec % 60;
   	result_min = (fly_sec / 60) % 60;
   	result_hour = ((fly_sec / 60) / 60) % 24 ;
   	result_day = ((fly_sec / 60) / 60) / 24;
 
   	printf(" %d day, %d hour, %d minute, %d second\n", result_day, result_hour, result_min, result_sec);
}   

으로 했는데요...
문제는 대략 50여 시간이 차이가 납니다. 분과 초는 정확하구요.
시간과 날짜가 오류가 나서 이렇게 질문드립니다.

아 그리고 localtime으로 현재시간을 출력하면 이상이 없었습니다.

cwryu의 이미지

윤년이 틀렸나 해서 봤지만 잘 모르겠어서 실행해 봤는데요. 맞게 잘 나오는데요? (50시간 차이라고 하시는 걸 보면 타임존때문도 아니고, day of the year의 카운트 시작이 0/1이냐때문에 착각하신 것도 아니실 텐데...)

$ echo 2007 | ./a.out; TZ=UTC date "+%j day, %H hour, %m minute, %S second"
현재 년도를 입력하세요 _ 285 day, 18 hour, 49 minute, 9 second
286 day, 18 hour, 10 minute, 09 second
$

----
익명이나 오래전 글에 리플은 무조건 -1

modestcode의 이미지

Quote:
man 2 time

NOTES에 보면 이 초를 일관성 있게 하기 위해서 단순히 년도가 4로 나누어지면 윤년으로 계산한다고 해 놨습니다. 거기 나와있듯이 자세한 것은 POSIX.1 Annex B 2.2.2를 보세요.
그러므로,
@@ -19,7 +19,7 @@ int main(void)
         //윤년 평년 구하는 부분.
    for(i = 1970; i < year ; i++)
    {      
-      if((i % 4) == 0 &&  (( i% 100) != 0) || ((i % 400) == 0))
+      if((i % 4) == 0)
       {
       check_plus_day = check_plus_day + 366;
    }

가 돼야 합니다.
그러면 이 프로그램에서 2007을 입력했을 때, sec_check은
TZ=UTC date "+%s" --date="2007-01-01 00:00:00"

결과와 같아야 합니다.
lifthrasiir의 이미지

놀라운(?) 사실이군요. 이 글 읽고 혹시나 해서 ISO C를 찾아 봤는데 다음과 같은 내용이 쓰여 있네요.

"time 함수는 현재의 시간을 결정한다. 반환되는 값의 형식은 unspecified[= 구현체에 따라 다를 수 있으며 문서화할 의무가 없다]이다." -- ISO/IEC 9899:1999 7.23.2.4 (2), 편의상 번역

결국 portable하게 현재 시간을 알아 내려면 localtime이나 gmtime을 써야 하는 게 맞겠군요.

IsExist의 이미지

mktime() 함수를 사용하세요.
struct tm 구조체를 time_t 로 변환해 줍니다.

현재 날짜와 년초 날짜를 각각 tm 구조체로 만들고 각각 mktime을 호출한 후
리턴된 time_t의 차이만 구하면 됩니다.
---------
간디가 말한 우리를 파괴시키는 7가지 요소

첫째, 노동 없는 부(富)/둘째, 양심 없는 쾌락
셋째, 인격 없는 지! 식/넷째, 윤리 없는 비지니스

이익추구를 위해서라면..

다섯째, 인성(人性)없는 과학
여섯째, 희생 없는 종교/일곱째, 신념 없는 정치

---------
간디가 말한 우리를 파괴시키는 7가지 요소

첫째, 노동 없는 부(富)/둘째, 양심 없는 쾌락
셋째, 인격 없는 지! 식/넷째, 윤리 없는 비지니스

이익추구를 위해서라면..

다섯째, 인성(人性)없는 과학
여섯째, 희생 없는 종교/일곱째, 신념 없는 정치

teshi의 이미지

다시 시도해봤습니다만... 이상하게 그 대로 나옵니다... 물론 시스템 시간은 정확하게 맞추었구요...
이상하네요;;;
댓글 달아주신 분들께 감사드리면서 ;ㅁ;

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.