mysql时间戳转换ymdhis,如何将日期和时间为AM / PM的字符串转换为24小时mysql时间戳格式...

I am trying to insert date and time into mysql datetime field from a string having following dd/mm/yyyy hh:mm:ss AM/PM format:

20/10/2014 05:39 PM

20/10/2014 05:39 AM

I know MYSQL timestamp format is yyyy-mm-dd hh:mm:ss or 0000-00-00:00:00:00

So if I do:

$s = substr("20/10/2014 05:39 PM", 0, 10);

$h = date("G:i", strtotime($s));

list($day, $month, $year, $hour, $minute) = split('[/ :]', "20/10/2014 05:39 PM");

echo $d1me = $year . '-' . $month. '-' . $day . ' ' . $h;

I get 2014-10-20 19:00

So I guess there is a problem with date_default_timezone_set() function, How to solve this and get expected result?

20/10/2014 05:39 PM -> 2014-10-20 17:39:00

20/10/2014 05:39 AM -> 2014-10-20 05:39:00

How to do it?

解决方案

MySQL already knows how to parse many different types of date strings natively, using the STR_TO_DATE() function in combination with format strings used by DATE_FORMAT().

So, I would not involve PHP in this process at all, and instead allow MySQL to parse the input itself.

The format string you need to use is %d/%m/%Y %h:%i %p, where the %p represents AM/PM.

You can use the entire expression right in your INSERT statement, passing the strings directly from PHP assuming you have validated their format already.

INSERT INTO your_table (timestamp_column) VALUES (STR_TO_DATE('20/10/2014 05:39 PM', '%d/%m/%Y %h:%i %p'));

...will correctly insert the DATETIME value 2014-10-20 17:39:00 into your table.

If you really prefer to do it in PHP first, use DateTime::createFromFormat() (PHP 5.3+) using the format string 'd/m/Y H:i A'

$d = DateTime::createFromFormat('d/m/Y H:i A', '20/10/2014 05:39 PM');

var_dump($d);

class DateTime#2 (3) {

public $date =>

string(26) "2014-10-20 17:39:00.000000"

public $timezone_type =>

int(3)

public $timezone =>

string(15) "America/Chicago"

To get a MySQL formatted date back out of it,

echo $d->format('Y-m-d H:i:s');

// 2014-10-20 17:39:00

If you are in the deeply unfortunate situation of having a PHP version older than 5.3, you can achieve similar results with strptime() but you'll need to assemble its array output into MySQL's string format.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值