zoukankan      html  css  js  c++  java
  • 007#验证日期格式

    验证日期是否有效,主要考虑闰年的情况,闰年的2月份有29天

    闰年规则:

    1、普通闰年:公历年份是4的倍数的,且不是100的倍数,为普通闰年。(如2004年就是闰年)

    2、世纪闰年:公历年份是整百数的,必须是400的倍数才是世纪闰年(如1900年不是世纪闰年,2000年是世纪闰年)

    本案例用将会调用到 003#规范日期格式

    脚本:

    #!/usr/bin/env bash
    # valid-date
    
    # 同目录存在normdate,用于规范化日期,后面将会调用到
    # 参考003#规范日期格式
    PATH=.:$PATH
    
    # 判断给定月份的有效天数
    exceedsDaysInMonth()
    {
      case $(echo $1 | tr '[:upper:]' '[:lower:]') in
        jan* ) days=31 ;;
        feb* ) days=28 ;;
        mar* ) days=31 ;;
        apr* ) days=30 ;;
        may* ) days=31 ;;
        jun* ) days=30 ;;
        jul* ) days=31 ;;
        aug* ) days=31 ;;
        sep* ) days=30 ;;
        oct* ) days=31 ;;
        nov* ) days=30 ;;
        dec* ) days=31 ;;
        * ) echo "$0: Unkown month name $1" >&2
            exit 1
      esac
      
      # 判断天数是否有效,有效返回0,无效返回1
      if [ $2 -lt 1 -o $2 -gt $days ]; then
        return 1
      else
        return 0
      fi
    }
    
    # 验证闰年
    isLeapYear()
    {
      year=$1
      if [ "$((year%4))" -eq 0 -a "$((year%100))" -ne 0 ]; then
        return 0
      elif [ "$((year%400))" -eq 0 ]; then
        return 0
      else
        return 1
      fi
    
    #  if [ "$((year % 4))" -ne 0 ]; then
    #    return 1
    #  elif [ "$((year % 400))" -eq 0 ]; then
    #    return 0
    #  elif [ "$((year % 100))" -eq 0 ]; then
    #    return 1
    #  else 
    #    return 0
    #  fi
    }
    
    # main 
    usage="Usage: $0 month day year
    Typical input formats are August 3 2019 and 8 3 2019"
    if [ $# -ne 3 ]; then
      echo -e "$usage" >&2
      exit 1
    fi
    
    # 规范日期
    newdate="$(normdate "$@")"
    if [ $? -eq 1 ]; then
      exit 1
    fi
    
    # 拆分规范后的日期格式,检验其合法有效性
    month="$(echo $newdate | cut -d  -f1)"
    day="$(echo $newdate | cut -d  -f2)"
    year="$(echo $newdate | cut -d  -f3)"
    
    msg1="$0: $3 is not a leap year, so Feb doesn't have 29 days."
    msg2="$0: bad day value: $month does't have $2 days."
    
    if ! exceedsDaysInMonth $month $2; then
      if [ "$month" = "Feb" -a $2 -eq 29 ]; then
        if ! isLeapYear $3; then
          echo $msg1 >&2
          exit 1
        fi
      else
        echo $msg2 >&2
        exit 1
      fi
    fi
    
    echo "valid date: $newdate"
    exit 0
    View Code
    *** 你必须十分努力,才能看起来毫不费力 ***
  • 相关阅读:
    微人事项目-mybatis-持久层
    通过外键连接多个表
    springioc
    Redis 消息中间件 ServiceStack.Redis 轻量级
    深度数据对接 链接服务器 数据传输
    sqlserver 抓取所有执行语句 SQL语句分析 死锁 抓取
    sqlserver 索引优化 CPU占用过高 执行分析 服务器检查
    sql server 远程备份 bak 删除
    冒泡排序
    多线程 异步 beginInvoke EndInvoke 使用
  • 原文地址:https://www.cnblogs.com/bigtree2pingping/p/12966633.html
Copyright © 2011-2022 走看看