php - 日期数组元素到 PHP 数组变量
问题描述
我有来自 for 循环的 HTML 代码(多个 datepicker)中的 datepicker 元素(来自数据库的数据)
它显示良好,让用户为不同的产品选择不同的日期。在提交时,通过 post 将这些日期分配给 php 变量。
但是该元素仍然是字符串而不是日期。如何在php中将字符串更改为日期?
<td colspan=2>
<input type="text"
name="expirydate[]"
id="expirydate<? echo $SNO;?>"
autocomplete="off"
class="expirydate"
value="<? $DateToday=date('Y-m-d');
$ShowDate1 = explode("-", $DateToday);
$ShowDate2 = "$ShowDate1[2]/$ShowDate1[1]/$ShowDate1[0]";
echo $ShowDate2; ?>"
/>
</td>
$(function(){
$('.expirydate').datepicker({ minDate: 0 });
});
$expirydate = $_POST["expirydate"];
for ($x=0; $x<=$TotalCount-1; $x++)
{
$expirydate1 = $expirydate[$x];
$n1 = explode("/", $expirydate1);
echo $n1[0] . "--" . $n1[1] . "--" . $n1[2] . "<br>";
$n2 = "$n1[2]-$n1[1]-$n1[0]";
$n22 = date_create($n2);
$n3 = date_format($n22,"Y/m/d H:i:s");
}
解决方案
According your code above $ShowDate2
is in the format of d/m/Y
.
Using DateTime::createFromFormat you can parse the date string into a DateTime object.
$date = DateTime::createFromFormat('d/m/Y', '27/11/2019');
If you want it formatted just use the format method on it: $date->format('Y-m-d')
.
If your $expirydate
is an array of dates in the mentioned d/m/Y
format, you can do the following:
$expirydate = [ '27/11/2019', '26/11/2019', '25/11/2019'];
$dates = array_map(function($date) {
return DateTime::createFromFormat('d/m/Y', $date);
}, $expirydate);
推荐阅读
- javascript - JavaScript 在不同的时间执行相同的函数
- c# - C# 使用 ScpClient 运行命令
- javascript - 对于模型 \"colt\"" 错误的路径 \"_id\" 处的值 \":5e1360c5edb2922570aa2611\" 转换为 ObjectId 失败
- php - 带有Curl的PHP中“whois.pir.org”的哪个命令?
- c# - 使用 autofac 注册 ImmutableArray
- microsoft-graph-api - 创建计划后获取 Microsoft Teams 组/团队的驱动器
- php - 在 php 的组合框中使用默认值
- javascript - React:`style` 属性需要从样式属性到值的映射,而不是字符串
- math - 哪个点在逆时针方向
- flutter - Flutter GridView.Builder 不滚动(高度问题)