Best way to make $date and $hour into a PHP date? - php

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

Related

How to update certain values of a php date string?

I have some date string values that I want to be able to update for checking against in some conditional statements. I want to update the hour, minute and seconds values to be at 23:59:59.
Say I have the variable $value which prints to
2017-03-08 00:00:00
How can I update the value to be
2017-03-08 23:59:59
?
Use DateTime.
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s',$value);
$dateTime->setTime(23,59,59);
$value = $dateTime->format('Y-m-d H:i:s');
http://php.net/manual/en/class.datetime.php
You could do many more things with the DateTime class.
Hi there this is the code below which you can use to update the time value:
your variable in php:
$value = "2017-03-08 00:00:00";
the html tag like so:
<input type="datetime-local" name="date" value="<?php echo date("Y-m-d\TH:i:s", strtotime($value)); ?>" />
This tag also generates a date and time picker, assuming you a running a compatible browser.
Note: In the future please show us your work and what you have achieved because you cannot expect someone to do it all for you, good luck!
In this simple case, you could probably leverage strtotime to get what you want:
$myDate = '2017-03-08 00:00:00';
$myTime = strtotime($myDate) + 86399;
echo date('Y-m-d H:i:s', $myTime);
Though in more difficult cases it would probably be better to use PHP's DateTime class:
$myDate = '2017-03-08 00:00:00';
$dt = new DateTime($myDate);
// Subtract one second
$dt->add(new DateInterval('PT86399S'));
// Output formatted result
echo $dt->format('Y-m-d H:i:s');
You could also look into Carbon for handling all of your date / time needs.

Splitting Datetime into a date and a time value

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

check if datetime from sql is today

I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}

mysql converting text input to datetime field

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

PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?

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;

Categories