C++中的日期验证和转换

Date Validation and Conversion in C++

本文关键字:转换 验证 日期 C++      更新时间:2023-10-16

我必须写2个函数。一个将日期作为字符串并检查其是否为 mm/dd/yy 格式;如果格式不正确,则应对其进行编辑以使其正确。另一个函数应将验证日期转换为"月 dd, 20yy"格式。

我很确定我可以处理第二个功能,但我在处理第一个功能时遇到了麻烦。我只是不知道如何检查它是否采用这种格式......有什么想法吗?

我以为这会起作用,但似乎没有...

更新的代码:

bool dateValidation(string shipDate)
{
    string temp;
    if(shipDate.length() == 8 )
    {
        if(shipDate[2] == '/' && shipDate[5] =='/')
        {
            int tempDay, tempMonth, tempYear;
            //Gather month
            temp = shipDate[0];
            temp += shipDate[1];
            //convert string to int
            tempMonth = temp.atoi;
            temp = "";
            //Gather day
            temp = shipDate[3];
            temp += shipDate[4];
            //convert string to int
            tempDay = temp.atoi;
            temp = "";
            //Gather year
            temp = shipDate[6];
            temp += shipDate[7];
            //convert string to int
            tempYear = temp.atoi;
            temp = "";
            if(tempMonth > 0 && tempMonth <= 12)
            {
                if(tempMonth == 9 ||
                   tempMonth == 4 ||
                   tempMonth == 6 ||
                   tempMonth == 11 ||)
                {
                    if(tempDay > 0 && tempDay <= 30)
                    {
                        if 30 days
                            }
                }
                else if(tempMonth == 2)
                {
                    if(tempDay > 0 && tempDay <= 28)
                    {
                        if 28 days
                            }
                }
                else
                {
                    if(tempDay > 0 && tempDay <= 31)
                    {
                        if 31 days
                            }
                }
            }
        }
    }
}

您需要检查 4 件事:

  • 有8个字符吗?如果没有,那么甚至不要费心检查其他任何东西。它的格式不正确。
  • 是第三和第五个字符"/"。如果没有,那么您仍然没有正确的格式。
  • 检查每对的有效值。一个月的天数介于 1 到 1 之间最多31个月,不超过12个月,月份范围从01到 12.年份可以是任意 2 位数字的任意组合。

这应该处理格式,但如果要确保日期有效:

  • 检查每个月的有效天数(1 月 31 日、2 月28-29...)并确实检查那些闰年。

这看起来很像我即将评分的项目......如果它是我即将评分的项目,您应该验证它是否符合公历标准。 1/1/2012 绝对有效,所以您可能想要做的,我希望您考虑的是创建一个 switch 语句来检查 1/12/2012 和 10/2/2012 等格式,因为这些格式是有效的。然后从中解析出月日和年。然后验证它们是否在公历的限制范围内。如果是我猜的类,您应该考虑将验证编写为与解析函数分开的函数。

所以先问一下日期是不是太长了,是不是太短了,如果不是哪个版本,再把 d m y 传递给验证函数。这种模块化将简化您的代码并减少指令。

类似的东西

布尔日期验证(字符串发货日期){ 字符串温度;

switch(shipDate.length())
{
     case(10):
        // do what  your doing
        verify(m,d,y);
        break;
     case(8):
        //dealing with single digits
        // verify 1 and 3 are '/' and the rest are numbers
        verifiy(m,d,y);
        break;
     case(9):
        //a little more heavy lifting here 
        // but its good thinking for a new programmer
        verifiy(m,d,y);
        break;
     default:       
      //fail message
        break;
}