猿问

从输入字段中减去小时和分钟

我有一个包含五个输入字段的表单:


name="MultiRoomFromDate"  //outputs the date in the following format "d-m-Y"

name="MultiRoomFromTimeH" // has a dropdown of "00" to "23"

name="MultiRoomFromTimeM" // has a dropdown of "00" to "59"



<select name="MultiFromDisplayTimeH" id="MultiFromDisplayTimeH" class="FormTime">

    <option value="0">0</option>

    <option value="3600">1</option>

    <option value="7220">2</option>

    <option value="10800">3</option>

    <option value="14400">4</option>

 </select>


<select name="MultiFromDisplayTimeM" id="MultiFromDisplayTimeM" class="FormTime">

    <option value="0">0</option>

    <option value="900">15</option>

    <option value="1800">30</option>

    <option value="2700">45</option>

</select>

如果我选择“MultiRoomFromDate”作为26-01-2020“,MultiRoomFromTimeH作为”09“,MultiRoomFromTimeM作为”00“,选择”MultiFromDisplayTimeH“作为”01“,将”MultiFromDisplayTimeM“选为”00“,并提交输出的表单:


FromDate = MultiRoomFromDate; //26-1-2020

FromHours = MultiRoomFromTimeH; //09

FromMins = MultiRoomFromTimeM; //00

DisplayHours = MultiFromDisplayTimeH; //3600

DisplayMins = MultiFromDisplayTimeM; //0

我需要做的是输出“FromDate,FromHours,FromMins”减去“DisplayHours”和“DisplayMins”作为Y-m-d H:i。


杨__羊羊
浏览 95回答 2
2回答

不负相思意

首先,通过删除属性来简化选择选项语法 - 这只会使您的标记更难一目了然地理解,并且对于我稍后将演示的日期时间计算来说,这将是不必要的。我还认为更简单的字段名称将是有益的。value<select name="subtractHours" class="FormTime">&nbsp; &nbsp; <option>0</option>&nbsp; &nbsp; <option>1</option>&nbsp; &nbsp; <option>2</option>&nbsp; &nbsp; <option>3</option>&nbsp; &nbsp; <option>4</option>&nbsp;</select><select name="subtractMinutes" class="FormTime">&nbsp; &nbsp; <option>0</option>&nbsp; &nbsp; <option>15</option>&nbsp; &nbsp; <option>30</option>&nbsp; &nbsp; <option>45</option></select>然后,使用 PHP 的 datetime 类来:从日期/时间值初始化日期时间对象减去提交的时间量将日期时间字符串调整为所需格式。代码:(演示)$fromDate = '26-1-2020';$fromHours = '09';$fromMins = '00';$subtractHours = '1';$subtractMins = '0';$format = 'Y-m-d H:i:s';$date = DateTime::createFromFormat('d-m-Y H:i:s', "{$fromDate} {$fromHours}:{$fromMins}:00");$date->sub(new DateInterval("PT{$subtractHours}H{$subtractMins}M"));echo $date->format('Y-m-d H:i');输出:2020-01-26 08:00为了稳定性/一致性,我将 as 秒添加到对象中,以防您想要将完整的日期时间戳插入到数据库中(这需要格式)。:00Y-m-d H:i:s当时间减法导致损失一天时,上述过程也将同样有效。(演示)$fromDate = '25-1-2020';$fromHours = '01';$fromMins = '30';$subtractHours = '6';&nbsp; // don't bother with 3600 precalculation$subtractMins = '45';// Output: 2020-01-24 18:45

料青山看我应如是

我完全重写了我的代码,现在我已使用以下代码解决了该问题:$DisplayTime = $FromTimeStamp - $FromDisplayHours - $FromDisplayMins;echo "DISPLAYTIME 1 ".$DisplayTime."<br/>";$DisplayDateTime = date("Y-m-d H:i", $DisplayTime);
随时随地看视频慕课网APP
我要回答