【问题标题】:php combining variables with a hypen in betweenphp将变量与连字符之间的组合
【发布时间】:2014-04-17 01:50:59
【问题描述】:

我想从我的表单中创建一个变量,它是 MySQL 中数据字符串的形式,看起来像 yyyy-mm-dd 我想使用连字符以便它可以以这种方式搜索它。

$year=$_POST['year'};
$mont=$_POST['month'];
$day=$_POST['day'];
$date=$year-$mont-$day;

【问题讨论】:

  • 尽管您可以将所有内容粘合在一起,但我建议您查看 PHP 的特定时间和日期函数(特别是 DateTime 类)以生成有效日期并生成始终符合您需要的输出。请注意,2014-5-202014-05-20 不同,用户可能不会发送实际转换为有效日期的输入。

标签: php mysql string variables combinations


【解决方案1】:

将三个变量合二为一?

 //your variables
 $year = $_POST['year'};
 $month = $_POST['month'];
 $day = $_POST['day'];

 //your variables combined
 $date = $year.'-'.$month.'-'.$day;

【讨论】:

    【解决方案2】:

    要确保它具有正确的“yyyy-mm-dd”格式,请使用sprintf()

    $date = sprintf('%d-%02d-%02d', $_POST['year'], $_POST['month'], $_POST['day']);
    

    假设年份在 1000 到 9999 之间。

    【讨论】:

      【解决方案3】:

      你的意思是像 2014-04-17 这样的格式吗? 在下面更改此代码

      $date=$year-$mont-$day;
      

      $date=$year . "-" . $mont . "-" . $day;
      

      【讨论】:

        【解决方案4】:

        有多种方法可以做到这一点。

        $date = "$year-$month-$day";
        
        $date = $year.'-'.$month.'-'.$day;
        
        $date = sprintf('%s-%s-%s', $year, $month, $day);
        
        // Example from the manual, enforces ISO 8601 format
        $date = sprintf("%04d-%02d-%02d", $year, $month, $day);
        

        【讨论】:

          猜你喜欢
          • 2011-07-19
          • 2019-05-15
          • 1970-01-01
          • 2017-12-29
          • 1970-01-01
          • 2014-07-20
          • 1970-01-01
          • 2019-01-02
          • 1970-01-01
          相关资源
          最近更新 更多