I have two inputs Time and Date. I want to convert these fields to one using php and insert them into a datetime field in mysql. I think I need to use a STR_TO_DATE. But I'm unsure how to do it. Thanks
Format
Time = 12:00 PM
Date = 2010-11-17
Since you plan to use PHP, you can directly set into a format that MYSQL will accept,
such as
$the_date = date('Y-m-d H:i:s', strtotime($date.' '.$time);
$sql = "INSERT INTO YOUR_TABLE SET COL_FOR_DATE_TIME='{$the_date}'";
$Time = "12:00 PM";
$Date = "2010-11-17";
$DateTime = $Date . " " . $Time;
$timestamp = date('Y-m-d H:i:s',strtotime($DateTime));
This PHP code to get a start and end date:
$datef = (date("Y-m-d H-i-s",mktime($_POST['hour'], 0, 0, $_POST['month'], $_POST['day'], $_POST['year'])));
$datel = (date("Y-m-d H-i-s",mktime($_POST['hour1'], 0, 0, $_POST['month1'], $_POST['day1'], $_POST['year1'])));
This was posted from a load of html dropdowns!
I know this doesnt exactly answer your question but it will give you a good foundation!
You should use a timestamp, it's a much more easily manipulated standard with just as much granularity as you need for your current setup.
As for "Converting" the table, that's pretty much impossible, you would need to make a new table, move the stuff over, drop the old one and rename the new one...
The STR_TO_DATE function is indeed a good option.
You could try something like this:
STR_TO_DATE('2010-11-17 12:00 PM', '%Y-%m-%d %h:%i %p')
Related
In my site, I have a bootstrap datepicker which allows user to pick date in format of MM/DD/YYYY (e.g: 05/12/2014). Then when this data is submitted, I used the following PHP code to convert it into Datetime type, then insert into start_date (DATETIME datatype) column in MySQL .
$start_date = date('Y-m-d', $_POST['start_date']);
the insert query in PHP does nothing with reformatting the date. It just simply insert into corresponding column.
However, instead of inserting '2014-05-12', the value inserted into database is '1970-01-01'. That's so weird to me. Can anybody tell me what's wrong here. Is this that I used incorrect PHP function or incorrect timezone setting or ...
Just do this:
$start_date = date('Y-m-d', strtotime($_POST['start_date']));
You could also use strtotime() on your $_POST.
$start_date = date('Y-m-d', strtotime('05/12/2014'));
try to use
$date = str_replace('/', '-', $_POST['start_date']);
$start_date = date('Y-m-d', strtotime($date));
For more :- Converting between illogically formatted dates (changing /slash/ to -dash- )
A simple question, but a little bit hard to search for...
What is the easiest and simplest way to get a PHP date, when I have $date (formated as HTML5 input type=date), and $hour (00 to 23).
I want the result to be $date = "2014-01-24 05:00" (MySQL)
$date = date("Y-m-d H:i");
Then you can use $date where ever the date is needed.
how about $formattedDate = date('Y-m-d H:i',strtotime($date.' '.$hour.':00'))
If this is going into a mysql Db you can do it right in the query
"INSERT INTO TABLE (`DATECOLUMN`) VALUES (
DATE_ADD(CURDATE(), INTERVAL '$hour' HOUR))"
Obviously don't forget to sanitize the inputs
So I have a field in my database called 'DateTime' and the following lines of code:
echo "Date/Time: ";
echo $row['DateTime'];
How do I format it so that instead of being like this:'2013-02-07 22:14:56', it will be like this: '07/02/13 - 22:14'
Thanks.
Alternatively you could use:
DateTime::createFromFormat('Y/m/d H:i:s',$row['DateTime']); this will give you a datetime object, which are quite nice to work with.
Another alternative would be to have MySQL format the DATETIME value as a string in the desired format, using the DATE_FORMAT function.
SELECT DATE_FORMAT(`DateTime`,'%d/%m/%y - %H:%i') AS `DateTime`
...
No change required to your PHP code except for the SQL text sent to the database server.
This approach can very efficient, and reduce the amount of code you need, if all you are doing with this string is displaying it. If you are doing any sort of manipulation on this value, then casting the string value returned from MySQL resultset into a datetime object is probably a better way to go.
A demonstration of the DATE_FORMAT function:
SELECT DATE_FORMAT('2013-02-07 22:14:56','%d/%m/%y - %H:%i') AS `DateTime`
DateTime
----------------
07/02/13 - 22:14
how to output date into Year textbox Month textbox Day textbox
$book_date = $myrow["Publication_Day"];
$book_year = Date("Y", strtotime($book_date));
$timestamp contains ur date & time in any format.....................
date('Y/m/d - H:i',strtotime($timeStamp));
echo date('d/m/y H:i', strtotime($row['DateTime']));
See date and strtotime for more detail on the functions from the docs
$mytime = strtotime('2013-06-07 22:14:56');
$newDate = date('m/d/y - G:i', $mytime);
echo $newDate;
Here's an alternative using DateTime. If you're working with timezones this code can be easily modified to handle that.
$datetime = new DateTime('2013-02-07 22:14:56');
echo $datetime->format('d/m/y H:i');
See it in action
Can someone give me a quick and dirty way to split a datetime (28-1-2011 14:32:55) into just the date (28-1-2011) and the time ( 14:32 ) or even better (2:32 PM) using PHP. Using a mySQL database as well.
Cheers
If you're using PHP > 5.2:
$myvalue = '28-1-2011 14:32:55';
$datetime = new DateTime($myvalue);
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
Prior to PHP 5.2 mhitza gave a good answer.
In php you can use the date and strtotime functions for easy extraction.
$datetime = "28-1-2011 14:32:55";
$date = date('Y-m-d', strtotime($datetime));
$time = date('H:i:s', strtotime($datetime));
if your source of data is MySQL:
SELECT DATE( date_field ) AS date_part, TIME( date_field ) AS time_part ....
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_time
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date
Edit :
to answer the question from comments (example):
WHERE DATE( date_field ) > '2017-01-01'
One simple instruction will do the trick
explode will transform datetime to an array
and list will sort the datetime array into its needed values
$datetime = "28-1-2011 14:32:55";
list($date, $time)=explode(' ', $datetime);
// check the result
echo "date:". $date;
echo "<br>time:". $time;
// further more you can easily split the date into
// year month and day
list($year, $month, $day)=explode('-', $date);
If you looking for a really quick and dirty solution.
$datetime = "28-1-2011 14:32:55";
$date_arr= explode(" ", $datetime);
$date= $date_arr[0];
$time= $date_arr[1];
if you want to parse in the date from your Mysql and you want to remove time
then you can use this function
$date1=date("Y-m-d",strtotime('$your database field'))
We can easily split DateTime(28-1-2011 14:32:55) into date and time in MySQL.
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",1) into #dateOnly;
select #dateOnly;
The output will be- 28-1-2011(Here we split the date from the DateTime)
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
select #timeOnly;
The output will be- 14:32:55(Here we split the time from the DateTime)
We can covert the time to am and pm format also
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
SELECT TIME_FORMAT(#timeOnly, "%h %i %s %p")into #time;
select #time;
The time format will become 02 32 55 PM
I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!
Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.
You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.
Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...
Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);
Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.
Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().
This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));
$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;