Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

date( ) returns 1970-01-01

Tags:

date

sql

php

picker

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));

with the following

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

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.

like image 949
the_arthemis Avatar asked Mar 23 '26 15:03

the_arthemis


1 Answers

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

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.

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');

// ...
like image 162
Sverri M. Olsen Avatar answered Mar 25 '26 06:03

Sverri M. Olsen