Vintion's blog

~夜黑路滑,社会复杂~

Next Second

| Comments

求下一秒

给定一个时间,求下一秒是什么时间

code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <string.h>

bool NextSec(int *nYear,int *nMonth,int *nDate,int *nHour,int *nMinute,int *nSecond)
{
  if(*nYear<0 || *nMonth>12 || *nMonth<0 || *nHour>23 || *nHour<0 || *nMinute<0 || *nMinute>59 || *nSecond<0 || *nSecond>59) 
    return false;
  int nDays;
  switch(*nMonth)
  {
  case 1:
  case 3:
  case 5:
  case 7:
  case 8:
  case 10:
  case 12:
    nDays=31;
    break;
  case 2:// 判断闰年
    if(*nYear%400==0|| (*nYear%100!=0&&*nYear%4==0)) {
        nDays=29;
    }
    else {
        nDays=28;
    }
    break;
  default:
    nDays=30;
    break;
  }
  if(*nDate<0 || *nDate>nDays) 
    return false;

  (*nSecond)++;  // 秒加1
  if(*nSecond>=60) // 秒满60,做出特殊处理,下面时,日,月等类同
  {
    *nSecond=0;
    (*nMinute)++;
    if(*nMinute>=60) 
    {
        *nMinute=0;
        (*nHour)++;
        if(*nHour>=24)
        {
            *nHour=0;
            (*nDate)++;
            if(*nDate>nDays)
            {
                *nDate=1;
                (*nMonth)++;
                if(*nMonth>12)
                {
                    *nMonth=1;
                    (*nYear)++;
                }
            }
        }
    }
  }
  
  return true;
}

int main()
{
  int nYear=2004,nMonth=12,nDate=31,nHour=23,nMinute=59,nSecond=59;
  bool res = NextSec(&nYear,&nMonth,&nDate,&nHour,&nMinute,&nSecond);
  if(res)
    printf("The result:%d-%d-%d %d:%d:%d",nYear,nMonth,nDate,nHour,nMinute,nSecond);
  else
    printf("Input error!/n");

    return 0;
}

Comments