简体   繁体   English

如何将时间戳转换为 html 日期输入字段值 PHP

[英]How to convert timestamp to html date input field value PHP

In my code, here is how i convert html date field values to unix timestamp before inserting to MySQL db which works fine:在我的代码中,这里是我如何在插入到 MySQL db 之前将 html 日期字段值转换为 unix 时间戳,它工作正常:

//HTML Code:
<div class="form-group">
From:
<input type="date" name="dateFrom" value="<?php echo date('Y-m-d'); ?>" required/>
</div>

<div class="form-group">
To:
<input type="date" name="dateTo" value="<?php echo date('Y-m-d'); ?>" required/>
</div>

//PHP Code to convert to Time Stamp:
<?php $post->unix_stamp = strtotime($_POST['dateFrom']);
$post->unix_stamp_ex = strtotime($_POST['dateTo']);
$post->save(); ?>

How do i convert the unix timestamp back to html input date value for editing?如何将 unix 时间戳转换回 html 输入日期值进行编辑? What i've tried:我试过的:

<input type="date" name="dateTo" value="<?php echo date("Y-m-d\TH:i:s",$post->unix_stamp_ex); ?>" required/>

Where $post->unix_stamp_ex is the unix timestamp value.其中 $post->unix_stamp_ex 是 unix 时间戳值。 (doesn't work for me, shows dd/mm/yyyy instead). (对我不起作用,而是显示 dd/mm/yyyy)。 My problem is how to get the underlying value, to display in the date input so users can edit it我的问题是如何获取基础值,以显示在日期输入中,以便用户可以对其进行编辑

The reason your input is showing a placeholder 'dd/mm/yyyy' is because it cannot read the format you gave it.您的输入显示占位符 'dd/mm/yyyy' 的原因是它无法读取您提供的格式。 It can't work with time, so you need to remove it from your code:它不能与时间一起工作,因此您需要将其从代码中删除:

value="<?php echo date('Y-m-d',$post->unix_stamp_ex); ?>"

This will show the date in the input.这将在输入中显示日期。

Also, mind that the displayed value will differ from the actual value format, as per my comment and RoussKS' answer.另外,请注意,根据我的评论和 RoussKS 的回答,显示的值将与实际值格式不同。

According to Mozilla Developer docs for input type date根据输入类型日期的 Mozilla 开发人员文档

The displayed date format will differ from the actual value — the displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.显示的日期格式将与实际值不同——显示的日期格式基于用户浏览器的区域设置,但解析的值始终格式为 yyyy-mm-dd。

[edit] Just noticed the comment response, was typing as El_Vanja commented [/edit] [编辑] 刚刚注意到评论回复,正在输入 El_Vanja 评论[/编辑]

Brother, I am able to convert the database string back to readable date time using the following method.兄弟,我可以使用以下方法将数据库字符串转换回可读的日期时间。

Solutions解决方案

$databaseTime = '2020-03-22 09:45:48';
$date = strtotime($databaseTime);

echo "DatabaseTime: " . $databaseTime . "<br>";
echo "Date in epoch: ".$date."<br>";
echo "Readable date: ".date("Y-m-d H:i:s",$date)."<br>";

Results结果

https://prnt.sc/rkmleq https://prnt.sc/rkmleq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM