Convert mm/dd/yyyy into mysql timestamp? - php

I've been trying for about two hours to get this working with no luck. I'm trying to convert a date that's entered like 11/18/2012 into a mysql timestamp but everything I've tried just ends up as either 0000-00-00 00:00:00 or NULL in the database :( I'm using PHP + MYSQL so a solution in either would be great

Try This
$release_date=$_POST['release_date'];
echo date("Y-m-d H:i:s",strtotime($release_date));

PHP's DateTime to the rescue!
$datetime = new DateTime($alternativeFormat);
echo $datetime->format('Y-m-d H:i:s'); // mysql format
It's also possible to leave the altering of the data by MySQL, but I advice against it. By using the DateTime object you leave your query open to support other formats aswell.

Use STR_TO_DATE:
SELECT TIMESTAMP(STR_TO_DATE('11/18/2012','%m/%d/%Y'))
http://sqlfiddle.com/#!2/d41d8/4363/0
You stated that you tried:
UNIX_TIMESTAMP(STR_TO_DATE('$release_date','%m/%d/%y'))
The reason this doesn't work is because UNIX_TIMESTAMP's return type is unsigned integer, not TIMESTAMP. This is why you can't insert it into a TIMESTAMP column

Have you tried strtotime(): http://php.net/manual/en/function.strtotime.php
Or exploding on '/' and then using mktime(): http://php.net/manual/en/function.mktime.php
$parts = explode('/', $date);
$timestamp = mktime(0, 0, 0, $parts[0], $parts[1], $parts[2]);
Or any of the other suggestions in answers posted here?

My favorite method:
$date = '10/1/2012';
$mysqlDate = date('Y-m-d', strtotime($date));

I would try something like this.
$sDate = '11/18/2012';
$aDate = explode('/', $sDate);
$sMySQLTimestamp = sprintf(
'%s-%s-%s 00:00:00',
$aDate[2],
$aDate[0],
$aDate[1]
);
var_dump($sMySQLTimestamp);
> string(19) "2012-11-18 00:00:00"

The correct answer will depend upon exactly what you're trying to do, but in most cases it is a combination of these things:
Use a DateTime object, rather than a string, to represent the timestamp in PHP. (Convert it on input rather than when writing to the database).
Use a database interface that has placeholders, and when filling in a value that's a DateTime, automatically converts them to the appropriate string format
This keeps you from having to convert to, or even know, the native format expected by MySQL.

can you enter that example date as 2012/11/18 ?
if yes use
select convert('2012/11/18' ,DATETIME)
or you can use
select convert(str_to_date('11/18/2012','%m/%d/%Y'),DATETIME)

Related

Get date from database in php

i am storing date and time in database using php using gmdate() function in format "Y-m-d H:i:s". for e.g.
2014-03-10 12:35:55
Now,on getting this data into a php variable,for e.g.
$temp=2014-03-10 12:35:55
can i extract and display only the DATE portion excluding the TIME portion??
I am new to date and time manipulation.Any help?
you can get directly the date from database like this
select DATE(column_datetime) as date from yourtable
As Pramod answered,
date('Y-m-d', strtotime($temp));
works.
date('Y-m-d', strtotime($temp));
The above statement returns the date from datetime format
The following code example is adapted by this thread: How to convert date to timestamp in PHP?
There you can also read why it is not safe to rely on strtotime (answer by daremon)
$temp = '2014-03-10 12:35:55';
$a = strptime($temp, '%Y-%m-%d');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
Edit
From the PHP manual
Note: This function is not implemented on Windows platforms.
Try this:
Echo date('Y-M-D', $var);

Convert "m/d/y" date from a form text input field to a mysql datetime "friendly" input?

So I have a problem. Trying to convert input from form text input field which is in the following format: 08/06/2013 to a value that can be inserted into mysql datetime column.
I have tried this
$startdate_timestamp = strtotime($this->startdate);
// $this->startdate is the value from the input field
$this->startdate = date("YYYY-MM-DD HH:MM:SS",$startdate_timestamp);
But it seems that it is not doing anything. Is there any other way than this that would work ? I am using Yii framework so that is why code looks weird :)
strtotime() is smart, but it's not psychic or a genius, and when it screws up, it screws up bigtime. Don't use it, especially with ambiguous formats like m/d/y. There's no guarantee it won't be treated as as d/m/y.
Use date_create_from_format() instead, which lets you explicitly specify the input format. This is far more reliable, since you'll be in control over how the d and m portions are handled:
$ts = date_create_from_format('m/d/Y', '08/06/2013');
$start_date = $ts->format('Y-m-d H:i:s');
Do it on insertion using MySQL query superpowers. PHP date functions are a PITA: INSERT INTO FOO (date_field) values (DATE_FORMAT($this->startdate, '%Y %M %D')); Hope that helps!
$this->startdate = date("Y-m-d H:i:s", strtotime($this->startdate));
This will put it in the YYYY-MM-DD HH:MM:SS format compatible with MYSQL.

How do I compare a user passed y/m/d string to date time in mysql?

I have a variable that a user specifies $start_date in format of y-m-d.
so let's say for example $start_date = '2011-10-27';
In my database I have a DATETIME field, let's call it sample_date that looks like this
2011-10-27 14:15:20
When I run sql query using $start_date.. do I have to convert to compare the dates such as
SELECT * from content WHERE sample_date >= $start_date
or should I convert it somehow first
You don't need to convert the value as long as you've validated the format, but you should definitely sanitize the input to prevent XSS attacks and other nastiness. A calendar drop-down would be good here as well.
EDIT:
Whoa now... I see you've edited your question and the formats are different. That changes everything! Michael's comment is the correct answer, use strtotime() function to convert the date to a unix timestamp, then recreate the date in the proper format needed... like so... date('Y-m-d', strtotime($start_date))
Simply replace slashes with dashes.
$start_date = str_replace('/','-',$start_date);
$start_date = mysql_real_escape_string($start_date);
Just append some zeros onto this:
$start_date = "2010-10-27";
$start_date .= " 00:00:00";
EDIT: Testing confirms that this is unnecessary. As long as the mysql column is DATETIME formatted, it understands "2010-10-27".
HOWEVER! Your example will throw an error, as Greater Than or Equal to should be written ">=", not "=>"

Date_format() ? Question help

If I have a MySQL table field of my one date with this format (09-13-2011 11:22:43), as I do for PHP to print with this format (09/13/2011 11:22:43) Sorry my ignorance I searched the php.net site but can not find something about my request, Apologies.
$mysql_date = '09-13-2011 11:22:43';
$date = DateTime::createFromFormat('m-d-Y H:i:s', $mysql_date);
echo $date->format('m/d/Y H:i:s');
Use:
date( "m/d/Y h:i:s", UNIX_TIMESTAMP($fieldname));
If your field is already timestamp use the following:
date( "m/d/Y h:i:s", $fieldname);
I may be wrong in saying this but I don't think theres a standard way in doing so, unless you want to save the date/time as a unix_timestamp. If you do then you can format the time in however you want using the php date() function. If you aren't then you can always use something like str_replace() on the times to get them to the format you want or even use regex if your feeling adventurous
MySQL's DATE columns format is fairly irrelevant. Just use DATE_FORMAT() to convert the date to a string that suits your needs.

convert date string to mysql datetime field

I have a bunch of records with dates formatted as a string such as '04/17/2009'
I want to convert them to a mysql datetime field
I plan to use a foreach loop to read the old date value and insert the newly formatted value into a new field in each record
what would be the best way to convert that string...I thought php might have a way to do it automatically?
thanks
First, convert the string into a timestamp:
$timestamp = strtotime($string);
Then do a
date("Y-m-d H:i:s", $timestamp);
If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.
I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.
UPDATE some_table
SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')
You can support other date formats by using other format specifiers.
Use DateTime::createFromFormat like this :
$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');
You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.
The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.
$time = strtotime($oldtime);
Then use date() to put it into the correct format.
I assume we are talking about doing this in Bash?
I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...
DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY
you also may want to read up on the date command in linux. It can be very useful:
http://unixhelp.ed.ac.uk/CGI/man-cgi?date
Hope that helps... :)
-Ryan
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
json_date ["05/11/2011"]

Categories