UTC時間轉本地日期時間的實現

根據時區,把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--;
			}
		}
	}
};


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章