convert date string to mysql datetime field - php

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"]

Related

Convert mm/dd/yyyy into mysql timestamp?

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)

How to format `23/05/2012` into insertable value in DATETIME column?

I have dates formatted as d/m/y. How can I insert them into a DATETIME column?
Use MySQL's STR_TO_DATE() function:
INSERT INTO my_table VALUES (STR_TO_DATE('26/5/12', '%e/%c/%y'))
You need to use php's date() function along with strtotime() to convert date to any format you want.
MySQL database stores the date in YY-MM-DD format for datetime datatype, so if for example you have a date
$date = '26/05/2012';
You can convert it by using date() and strtotime()
$formatDate = date('Y-m-d', strtotime('26/05/2012'));
This will convert the date from 26/05/2012 to 2012-05-26 which then can be inserted into the database.
If you are using a timestamp datatype to store the date in your database, then all you need is to convert the current date into unix timestamp and store in database for example.
$date = strtotime('26/05/2012');
//this will convert the date to unix timestamp
Update:
as pointed out by #wallyk (thank you), strtotime() does not handles dd/mm/yy format. the fix is to replace the slash / by -m below code should work for you.
date('Y-m-d', strtotime(str_replace('/', '-', '26/05/2012')));
Try this:
$mysqldate = date("m/d/y g:i A", $datetime);
$date = date('d/m/Y');
$date = strtotime($date); //in unix time stamp format
Basically american date format is MM/DD/YYYY and you are providing DD/MM/YYYY so thats why startotime() returns you a null values on this input; and i prefer you must follow standard date format of american (MM/DD/YYYY) because if you are using mentioned format of date that will create more problems as well in different places ..
if you check by this
echo date('Y-m-d', strtotime('05/26/2012') );
and it is working fine ..
you could change your DATE column into a String Column and insert the data when ever you want 2 check if the date is right you can use a regular expression to do so

Convert or Extract Year, Month and Date from a string in PHP

All,
I have the following string:
$dateTime = '2013-09-15T00:00:00.000Z';
Is there a function to extract Year, Month and Date from the above string, so the result looks like the following:
$yearMonthDate = '2013-09-15';
Thanks
You could convert your datetime to a timestamp using strtotime() and then convert it back into a formatted date using this kind of syntax:
date("Y-m-d", strtotime($myOriginalDate))
substr or DateTime or strtotime+date
Since the first string is actually a standard, you can just use substr:
$yearMonthDate = substr($dateTime, 0, 10);
However, that would be kind of a hack and would obviously break if the format of $dateTime were to change. So, you might want to look into the PHP DateTime class instead.

How can i convert a date in php to SQL format ? (and insert it)

I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.
My date is in the format of: 28/01/2008
When I try to insert it to the SQL, I get just zeroes.
So how can I convert it properly?
$new_date = date('Y-m-d', strtotime($old_date));
Explanation
strtotime() will try to parse a string ($old_date in this case) and understand what date it is. It expects to be given a string containing an English date format or English textual datetime description. On success it will return a Unix timestamp (the number of seconds since January 1 1970). Now we have got a point in time out of that string.
date() then will turn this previously obtained point in time to a format, described in the first parameter, in the example above it is the 'Y-m-d'
Y — A full numeric representation of a year, 4 digits
m — Numeric representation of a month, with leading zeros
d — Day of the month, 2 digits with leading zeros
- — literally the minus symbol
Here's a full list of characters you can use in the format parameter string
I'm trying to insert a date , lets say
CURDATE() to an sql DateTime field.
$timestamp = strtotime($old_date);
$mydate = date('Y-m-d H:i:s', $timestamp);
Since you're using the European date notation (dd/mm/yyyy) the strtotime function will return 0 (which in turn will be converted to 1970-01-01 by date) if you don't use - or . as separator.
So if you want to use strtotime, then you will have to change your date strings just a bit :
$olddate = '28/01/2008';
$newdate = strtotime(str_replace('/', '-', $olddate));
$newdate should now contain '2008-01-28'...
join('-',array_reverse(explode('/',$date)))
to get the standard YYYY-MM-DD Mysql date format.
or just use MySQL' DATE_FORMAT
I'm trying to insert a date , lets say CURDATE() to an sql DateTime field.
Why don't you use the MySQL function directly?
insert tbl (id, other, datecol)
values(NULL, 'abcdef', CURDATE());
My date is in the format of: 28/01/2008
If it is not CURDATE() you want, but is a PHP variable in dd/mm/yyyy format instead, then see this MySQL man page for how to format the literals. Safe formats are YYYY-MM-DD and YYYYMMDD without time.
$date = '28/01/2008';
$query = "insert tbl (id, other, datecol)
values(NULL, 'abcdef', '" . date('Ymd', strtotime($date)) . "');";
Note: yyyymmdd is also a valid format in SQL Server.

PHP: Best way to convert a datetime to just time string?

I have a datetime that I pulled from the database that looks like this: 2000-01-01 08:00:00
Now I need to convert it so all I have left is: 08:00:00
What is the best way to do this?
substr('2000-01-01 08:00:00', 11);
You could use
substr($timestamp, -8);
you can also use the php strtotime function to turn it into a datetime object, then use the format method on it to get a pretty representation however you want. That way you can put in am/pm, do 24 hour or 12 hour, do whatever you want with the date, etc.
$date = strtotime('2000-01-01 08:00:00');
echo $date->format('H:i:s');
I should have thought of this earlier...easiest way would be to use the MySQL TIME() function to only select the time in the first place.
You can use date and enter the needed time format after parsing timestamp to str
date('h:i a', strtotime('2000-01-01 08:00:00'))

Categories