Code implementation of DateTime structure and string conversion

  • Problem Description

Customize a DateTime structure, the code is as follows:

//定义DateTime结构体
struct DateTime
{
	short year;
	short month;
	short day;
	short hour;
	short minute;
	short second;
};

How to convert the DateTime object into a string format such as "YYYY-MM-DD hh:mm:ss", or use the string to assign a value to the DateTime object to facilitate time comparison.

  • solution

Define a conversion function to convert a string into a DateTime structure , the code is as follows:

//接受3个参数,分别为字符串首地址,起始位置,计算长度
short SubStringToShort(const char *str, int begin, int len)
{
	int res = 0;
	for (int i = begin; i < begin+len; ++i)
	{
		int tmp = str[i] - '0';	//将字符型转化为整型
		res *= 10;
		res += tmp;
	}
	return (short)res;
}


//将字符串转换为DateTime结构体
DateTime *StringToDateTime(const char *str)
{
	DateTime *dt = new DateTime();

	//字符串必须符合特定格式(YYYY-MM-DD hh:mm:ss)
	int len = strlen(str);
	if (len != 19)
	{
		cout << "Invalid time string: " << str << endl;
		return nullptr;
	}
	//给year成员赋值
	short *p = (short *)dt + 1;
	dt->year = SubStringToShort(str, 0, 4);
	for (int i = 0; i < 5; ++i)
	{
		//给DateTime剩余的成员赋值,以short指针类型后移来获取成员内存地址
		*(p+i) = SubStringToShort(str, 5+i*3, 2);
	}

	return dt;
}

Convert the DateTime structure to a string , the code is as follows:

//将DateTime结构体转换为字符串
char *DateTimeToString(const DateTime *dt)
{
	char *str = new char[19];
	//使用sprintf库函数,格式化字符串,注意格式控制符的使用
	sprintf(str, "%04d-%02d-%02d %02d:%02d:%02d", dt->year, dt->month, dt->day, 
		dt->hour, dt->minute, dt->second);
	return str;	
}
  • to sum up

This solution is relatively simple and requires a specific string format.

Under normal circumstances, the DateTime structure in this example is of short type because the member variables are of type short, so the ordering in the memory is from low byte to high byte, and you can use the short pointer increment method to obtain each member variable Address and assign values.

 

 

 

Guess you like

Origin blog.csdn.net/gkzscs/article/details/82943780