【问题标题】:Using PHP to insert/output dates and time in mysql?使用 PHP 在 mysql 中插入/输出日期和时间?
【发布时间】:2011-03-21 07:33:57
【问题描述】:

我不知道为什么这么混乱,也许是因为用mysql和php输出/输入日期和时间的方法太多了。我只想让用户以这种格式输入日期

MM/DD/YYYY 

并让它以这种格式输出

Month Name - Date

对于时间,我希望用户从选择字段中选择时间,从下午 1:00 开始。并减少 30 分钟,所以它将是下午 1:30,下午 2:00 ......我想以某种方式将其插入 MySQL 并将其输出为下午 1:30。也不知道该怎么做。

【问题讨论】:

  • 您可以做到的一种方法是将时间戳存储在 mysql 中,然后使用 php 的日期函数输出它(在php.net/manual/en/function.date.php 阅读更多内容)。
  • 好吧,这是有道理的,我知道如何将当前时间存储在 mysql 中,但是我如何将预选的时间(例如下午 1:30)存储到 mysql 中。
  • 这取决于您需要对预先选择的时间下午 1:30 做什么,例如,如果您想在每天下午 1:30 通知用户,那么与 00:00 的时间戳差异到下午 1:30 将是 int(48600) ...
  • 我想我在问你如何从

标签: php mysql date time


【解决方案1】:

在数据库中存储日期格式并能够以您想要的方式显示它的最佳方法是使用time()date() 函数。

在你的数据库中存储日期时,你应该使用 time(),它会生成一个像这样的字符串 -> 1300695900。这个小字符串包含日期和时间

然后您可以使用日期以任何您想要的方式显示它:

$time = time();//you would normally get this from the database
date('d M Y', $time); //outputs 21 Mar 2011
date('m-d-y', $time); // outpus 03-21-2011

等等……

编辑: 要回答您的最后一个问题,您只需获得不同的值,将其粘在一起(串联),然后使用 strtotime()

$date = $_POST['date']; // eg 03/03/2011
$time = $_POST['time']; // eg 1:30
$daypart = $_POST['daypart']; // eg PM
$date_time = $date.' '.$time.' '.$daypart;
$strtime = strtotime($date_time);
echo date('d M Y - h:i', $strtime);// outputs 03 Mar 2011 - 01:30

【讨论】:

  • 好的,我了解从数据库中获取日期并以您想要的方式输出。但是假设用户将“2011 年 3 月 25 日”放在文本字段中,您将如何将其存储在 mysql 中,因为日期格式为 YYYY-MM-DD。有没有一个php函数可以把它转换成那种格式?
  • 在发送到数据库之前使用函数 strtotime()
  • 好吧,终于解决了,所以我剩下的唯一问题仍然是“你如何从
猜你喜欢
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 2011-02-25
  • 1970-01-01
相关资源
最近更新 更多