Splitting Datetime into a date and a time value - php

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

Related

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

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

subtract time away from a php date time

I have a report I built but the problem is the datetimes in the database for the 3 major events are the same as the system processes then so fast, there is no easy way about it as I aggregate data from 4 servers into one jquery datatable and sort by date time decending.
So my question is how can I take a variable in PHP (string of mysql format date time), and reduce it by 1 second?
dognose answer is fine. Find below a method using DateTime.
For those who are not too confident about strtotime :-)
$string = "2013-06-26 18:00:00";
$date = DateTime::createFromFormat('Y-m-d H:i:s', $string);
$date->sub(new DateInterval('PT1S'));//substract 1 sec
echo $date->format('Y-m-d H:i:s'); //print : 2013-06-26 17:59:59
Doc about "PT1S" here (this can be read as Period Time 1 second)
use date along with strtotime should do the trick:
http://php.net/manual/de/function.strtotime.php
$string = "2013-06-26 18:00:00"; //can have any (valid) format
$subSeconds = 1;
$date = date("Y-m-d H:i:s", strtotime($string . " - {$subSeconds} second"));
echo $date."<br />"; //2013-06-26 17:59:59

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

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

Find difference between two dates in PHP or MySQL

This query does not return the records for january, but it returns records for february.
SELECT EventAsstCharged,CustomerName,EventID ,EventName,EventExpectedCharges,EventActuallyCharged,EventUserCharged,date_format(EventDate,'%d-%m-%Y') as EventDate ,EventTime FROM tblevent WHERE Status=1 AND date_format(EventDate,'%d-%m-%Y') between '01-01-2011' AND '20-02-2011' AND EntryUser=2 AND Status=1 ORDER BY EventID DESC
How to find the age between two dates using PHP or MySQL?
2009-09-24 21:09:36 2010-03-04 13:24:58
<?php
$diff = strtotime('2010-03-04 13:24:58') - strtotime('2009-09-24 21:09:36');
echo "Difference is $diff seconds\n";
$days = floor($diff/(3600*24));
echo "Difference is $days days\n";
You can also do it at the database level using the DATEDIFF() function.
http://www.w3schools.com/SQl/func_datediff_mysql.asp
You can use this excellent function by Added Bytes to find it, I think.
echo datediff('yyyy', '2009-09-24 21:09:36', '2010-03-04 13:24:58);
Check out the function parameters for more information.
I found that the easiest way to find the difference between two dates is this one:
<?php
// Get current time, or input time like in $date2
$date1 = time();
// Get the timestamp of 2011 July 28
$date2 = mktime(0,0,0,7,28,2011);
?>
<?php
$dateDiff = $date2 - $date1;
$fullDays = floor($dateDiff/(60*60*24));
echo "$fullDays";
?>
Source: http://www.phpf1.com/tutorial/php-date-difference.html
function dateDiff($endDate, $beginDate)
{
$date_part1=explode(" ", $beginDate);
$date_part2=explode(" ", $endDate);
$date_parts1=explode("-", $date_part1[0]);
$date_parts2=explode("-", $date_part2[0]);
$start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
return $end_date - $start_date;
}
I fixed my ticket age using the following MySQL query.
DATEDIFF(CURDATE(),SUBSTR(ticket.created,1,10)) AS ticket_age

Categories