您的位置:首页 > 其它

UTC时间转本地日期时间的实现

2014-07-25 15:45 316 查看
根据时区,把UTC时间转换为本地时间。很简单,看代码吧

struct DATETIME
{
	uint16 year;
	uint8 month;
	uint8 day;
	uint8 hours;
	uint8 minute;
	uint8 seconds;
	uint8 microsecond;

	DATETIME()
	{
		clear();
	}

	void clear()
	{
		year = 1970;
		month = 1;
		day = 1;
		hours = 0;
		minute = 0;
		seconds = 0;
		microsecond = 0;
	}

	/*!< 根据指定时区转为当前日期和时间。Ex: 转为北京时间 -> transToLocal(8)*/
	void transToLocal(int8 timezone)
	{
		uint8 nLastDayOfMonth = 0;//每个月的最后一天
		if(timezone == 0)
		{
			return;
		}
		hours += timezone;

		if (hours > 23)
		{
			hours -= 24;
			day++;

			switch (month)
			{
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				nLastDayOfMonth = 31;
				break;
			case 2:
				if (((0 == year % 4) && (0 != year % 100)) || (0 == year % 400))
				{					
					/*!< 闰年的2月有29天*/
					nLastDayOfMonth = 29;
				}
				else
				{
					nLastDayOfMonth = 28;
				}
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				nLastDayOfMonth = 30;
				break;
			default:
				return;
			}
			if (day > nLastDayOfMonth)
			{
				day = 1;
				if(month == 12)
				{
					month = 1;
					year++;
				}
				else
				{
					month++;
				}
			}
		}
		else if(hours < 0)
		{
			hours += 24;
			if(day == 1)
			{
				switch (month)
				{
				case 1:
					/*!< 处理1月1日*/
					day = 31;
					month = 12;
					year--;
					return;
				case 3:
				case 5:
				case 7:
				case 8:
				case 10:
				case 12:
					nLastDayOfMonth = 31;
					break;
				case 2:
					if (((0 == year % 4) && (0 != year % 100)) || (0 == year % 400))
					{
						nLastDayOfMonth = 29;
					}
					else
					{
						nLastDayOfMonth = 28;
					}
					break;
				case 4:
				case 6:
				case 9:
				case 11:
					nLastDayOfMonth = 30;
					break;
				default:
					return;
				}
				month--;
				day = nLastDayOfMonth;
			}
			else
			{
				day--;
			}
		}
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: