I have a collection of time records in a database in the format '09:51:06' (hour, minute, second).
I have a query which retrieves a bunch of these times from the database, but I only care for the Hour reference.
How can I get rid of the rest of the string and ad just the hour into an array? So in the example above, I just want to keep '09'.
I've looked into exploding and substrings, but can't seem to figure it out.
Thanks.
Exploding the string would look like this (you probably want to add intval() to be able to use it as a real number):
$hours = array_shift(explode(':', '09:51:06'));
But you are probably looking for the right query instead of doing this afterwards. If you are dealing with a time-type, you can use MySQL's date and time functions (HOUR() in this case):
SELECT HOUR(`time_column`) AS `hour` FROM `your_table`
Or from the database itself
SELECT TIME_FORMAT(field_name, '%H') as return_hour from table_name
$time_string='09:51:06';
$your_array[$array_index]=substr($time_string, 0, 2);
for more info on substr
I guess you can do this either thru string manipulation or time/date. Any worthwhile date way would be on the SQL side, PHP has mktime and date functions but you would have get the hour you're looking for intermediately along the way if you were to construct a date anyway
String
$thisHour = array_shift(explode(':', $timeString)); //this gets hour
$thisHour - substr($timeString, 0, 2); // or this
$hours[] = $thisHour; //this adds to array
Related
I want to capture data that took place at the same hour and minute 24 hours ago. the formula below does not work. what could be the truth?
I will draw the date range in a single line, not listing.
$now=time();
$24hrb=$now-(24*60*60);
$que = $connc->query("select * from table where datetime='$24hrb';")
In my opinion it would be best to do this all in SQL. You can use the mysql intervals options to reduce by 1 day then like and substr to trim the seconds off and only pull the datetime through the minute value.
select * from table where datetime like concat(substr((now() - interval 1 day), 1, 16), '%')
The substr is taking from a string like this:
2021/01/22 11:12:21
^ ^
and concat throws the wildcard on the end so anything after that matches. So your like is processed as:
2021/01/22 11:12%
$24hrb=time() - (24*60*60);
This is a Timestamp value. But you state in comments:
yes. datetime format Y-m-d H:i:s
So what you actually should be doing if you insist on using this method is converting your datetime to a Unix timestamp:
$que = $connc->query("SELECT * FROM table
WHERE UNIX_TIMESTAMP(`datetime_column`) = '".(int)$24hrb."'");
This is much better and easier to read than messing around with concatenations and string manipulations.
Further,
You can extend this action using the MySQL BETWEEN keyword so that you can get the values found between the range of times, say +/- 30 seconds. so:
$que = $connc->query("SELECT * FROM table
WHERE UNIX_TIMESTAMP(`datetime_column`)
BETWEEN ".($24hrb - 30)." AND ".($24hrb + 30));
I have a special requirement where need to sum time columns, but for few record sum time is coming '08:60:02' so i need to get it as '09:00:02'. I tried to convert it to seconds first and then convert back to h:m:s but it's giving null as result.
$a = date_create_from_format("H:i:s", "08:60:02");
echo $a->format("H:i:s");
shows
09:00:02
you can try mysql functions like
SELECT round((SUM((08:60:02))/60)/100, 1);
I have a query that is returning a grid. One of the columns brings back a column with a date, like this:
echo "<td>{$Row[ETA]}</td>";
This displays the ETA from the database like this:
2013-10-30 20:00:0
I basically want to remove the TIME portion and just keep the date. Can this be done in the TD or do I have to the conversion elsewhere? I would like to just do the conversion within the cell, if possible.
Let me know how this can be done.
You can use the strtotime() and date() functions to achieve this!!!
date("Y-m-d", strtotime($Row[ETA]));
Well! if you want to get just date then you should use this function in your query
DATE(date_field)
as this will return only date from the datetime column
Ideally you should listen to the suggestion by JohnConde because it will limit your overhead between the database and your script but you can also substr() on the fly if you wish like this:
echo "<td>".substr($Row['ETA'], 0, 10)."</td>";
You have to echo it differently:
$eta = $Row['ETA'];
$etaDate = date("Y-m-d", strtotime($eta));
//now use $etaDate
You can use the date function to format the time, as what you're getting is a date as a string, you can use strtotime.
I think the format you're looking for is: date("Y-m-d", strtotime($Row["ETA"]));, you can either parse that into a variable and save it there, or you can concatenate the results together for the final string.
have a database with data and time
example: 2013-06-04 08:20:00
need to convert that to
example: 1378478351000
so i can add that number to jquery script event calendar
when i use this php code
$exc_date = $row_Recordset1['exc_date'];
$exc_date = microtime(true) *1000 ;
echo $exc_date;
it works right but it shows me the current date and time not the date and time saved at database,
can somone please help , thanks
If you want to avoid the calculations in PHP, add a computed column using unix_timestamp and str_to_date to your query:
select (
unix_timestamp(str_to_date(TimeStrColumnName, '%Y-%m-%d %H:%i:%s')) * 1000)
as utime,
# ... the rest of your query as before
if the MySQL column is already a date/time field (instead of a string), this will do it:
select (unix_timestamp(TimeStampColumnName) * 1000) as utime,
# ... the rest of your query as before
Of course it does, as you overwrite the database values in the second line by putting microtime instead in it.
You will not be able to get the microtime, when you just have the format of date in the database - so you should use 0. microtime is returning the value of the actual microtime at the moment.
You should do something like that to get time + microtime:
$exec_date = strtotime($row_Recordset1[exec_date"]) . "000";
More information here. The problem with this is, that you will get it as a string, so you will need to convert it to an integer:
$exec_date = (int) $exec_date;
Hope it helps you.
I am rebuilding a web application from an old one with many inconsistencies. I have to migrate all the data over from the old database to our new structure.
In the old database, dates were stored in the MySQL DB as VARCHAR. We are based in the UK, so dates were written in the format DD/MM/YYYY. I need to convert these dates to MySQL's native DATE() format.
Problem is this - PHP defaults to assuming the dates are in 'American' format (MM/DD/YYYY) because they were originally split with / rather than - - and - forces PHP to assume they are 'European' format.
I am doing this so far to convert them:
$start_date = date('Y-m-d', strtotime($query->row('startdate')));
Where $query->row('startdate') is the column in the old database which was storing the dates. Problem is, I need to first switch all the 21/03/1994s to 21-03-1994.
How can I do this?
$start_date = date('Y-m-d', strtotime(str_replace('/', '-', $query->row('startdate'))));
Or better yet - just change the data in the database:
UPDATE `table` SET `startdate` = REPLACE(`startdate`, '/', '-');
... and then convert the field to type DATE.
---- EDIT ----
Actually, Col. Shrapnel has a point ... I'd overlooked the fact that the date needs reversing as well so it's YYYY-MM-DD; assuming the original date is in the format DD/MM/YYYY a better query might be something like:
UPDATE `table` SET `date` = CONCAT(SUBSTRING(`date`, 7), '-', SUBSTRING(`date`, 4, 2), '-', SUBSTRING(`date`, 1, 2))
Which will reverse the component parts into a string that can be converted to a DATE ... it won't quite work if the original date string doesn't use leading zeroes 1/6/2011 for instance... would need to do something a little cleverer in that case.
WHY bother with all this date time stuff when you need mere a simplest string manipulation of 2 moves long?
$tmp = explode("/",$query->row('startdate'));
$date = "$tmp[2]-$tmp[1]-$tmp[0]";
but, as chris said, you dno't have to involve PHP in this operation as you can convert it using single SQL query using similar string manipulations in the query.
MySQL has a Replace() function that may be the easiest way to do this.
This is the 5.0 API reference:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
Use str_replace like this:
$start_date = date('Y-m-d', strtotime(str_replace('-','/',$query->row('startdate'))));
That is of course ugly and quick solution - YMMV.
If you're bound to PHP, why not parse the data, normalize it and then continue? E.g. with sscanf:
$r = sscanf($varcharDate, '%d/%d/%d', $day, $month, $year);
if ($r !== 3)
{
throw new Exception(sprintf('Invalid date format given: %s', $varcharDate));
}