C++:编写函数,显示当前时间

#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

/** Determine if it is a leap year */
bool isLeapYear(int year)
{
  if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
    return true;

  return false;
}

/** Get the total number of days from Jan 1, 1970 to the specified year */
int getTotalDaysInYears(int year)
{
  int total = 0;

  // Get the total days from 1970 to the specified year
  for (int i = 1970; i <= year; i++)
  {
    if (isLeapYear(i))
      total = total + 366;
    else
      total = total + 365;
  }

  return total;
}
int getNumOfDaysInMonth(int year, int month)
{
  if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
    return 31;

  if (month == 4 || month == 6 || month == 9 || month == 11)
    return 30;

  if (month == 2)
    if (isLeapYear(year))
      return 29;
    else
      return 28;

  return 0; // If month is incorrect.
}

/** Get the total number of days from Jan 1 to the month in the year */
int getTotalDaysInMonths(int year, int month)
{
  int total = 0;

  // Add days from Jan to the month
  for (int i = 1; i <= month; i++)
    total = total + getNumOfDaysInMonth(year, i);

  return total;
}

int main()
{
  // Obtain the total seconds since the midnight, Jan 1, 1970
  long totalSeconds = time(0);

  // Compute the current second in the minute in the hour
  int currentSecond = (int)(totalSeconds % 60);

  // Obtain the total minutes
  long totalMinutes = totalSeconds / 60;

  // Compute the current minute in the hour
  int currentMinute = (int)(totalMinutes % 60);

  // Obtain the total hours
  long totalHours = totalMinutes / 60;

  // Compute the current hour
  int currentHour = (int)(totalHours % 24);

  // Compute the total days
  int totalDays = (int)(totalHours / 24);
  if (currentHour > 0) totalDays++;

  // Obtain Year
  int currentYear = 2000;
  do
  {
    currentYear++;
  }
  while (getTotalDaysInYears(currentYear) < totalDays);

  // Obtain Month
  int totalNumOfDaysInTheYear = totalDays - getTotalDaysInYears(currentYear - 1);
  int currentMonth = 0;
  do
  {
    currentMonth++;
  }
  while (getTotalDaysInMonths(currentYear, currentMonth) < totalNumOfDaysInTheYear);

  // Obtain Day
  int currentDay = totalNumOfDaysInTheYear - getTotalDaysInMonths(currentYear, currentMonth - 1);

  // Display results
  cout << "Current date and time is " << currentMonth << "/" << currentDay <<
    "/" << currentYear << " " << currentHour+8 << ":"
      << currentMinute << ":" << currentSecond << " GMT" << endl;

  return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值