date()返回1970-01-01 [英] date( ) returns 1970-01-01

查看:484
本文介绍了date()返回1970-01-01的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下格式的mm/dd/yyyy的jquery datepicker,但是对于sql db,我需要使用它为yyyy-mm-dd,所以我正在使用它.

I am using a jquery datepicker with the following format mm/dd/yyyy but I need it to be yyyy-mm-dd for the sql db so I am using this.

   $date  = date("Y-m-d",strtotime($startdate));

带有以下内容

 $query = "INSERT INTO complete_table ( name, startdate) VALUES ('$_POST[name]', '$date')";

不幸的是,无论输入什么,我都在db中注册了1970-01-01. 有什么想法我做错了吗?非常感谢您的帮助.

Unfortunately I register 1970-01-01 in the db regardless of what the input is. Any idea on what I am doing wrong? Thank you so much for the help.

推荐答案

date()取回1970-01-01时,表示时间戳不正确.该日期是 UNIX时代.

When you get 1970-01-01 back from date() it means that the timestamp is incorrect. That date is the UNIX epoch.

当涉及到Javascript(在这种情况下为日期选择器)时,您应始终确保所获得的实际上是您期望的.简单地将其传递通过strtotime()会引起类似您在此处遇到的问题.

When it comes to Javascript (in this case a datepicker) you should always make sure that what you get is, in fact, what you expect it to be. Simply passing it through strtotime() will cause problems like the one you have here.

一种处理日期的好方法是使用 datetime 扩展名.它有一个静态方法 DateTime::createFromFormat ,该语法可以让您解析使用任何格式的任何日期:

One good way to handle dates is using the datetime extension. It has a static method, DateTime::createFromFormat, that will let you parse any date using any format:

// The value from the datepicker
$dpValue = '12/30/2013';

// Parse a date using a user-defined format
$date = DateTime::createFromFormat('d/m/Y', $dpValue);

// If the above returns false then the date
// is not formatted correctly
if ($date === false) {
    header('HTTP/1.0 400 Bad Request');
    die('Invalid date from datepicker!')
}

// Using the parsed date we can create a
// new one with a formatting of out choosing
$forSQL = $date->format('Y-m-d');

// ...

这篇关于date()返回1970-01-01的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆