How to get Hours from Date in PHP & Cakephp? - php

I want to get Only Hours From date by using PHP & Cakephp function.
$date = "2011-07-26 20:05:00";
$hours = ?

Use the Datetime class (PHP 5.3 or higher).
$dt = DateTime::createFromFormat("Y-m-d H:i:s", "2011-07-26 20:05:00");
$hours = $dt->format('H'); // '20'

By hours I'm assuming you mean if the time is 8PM or 20:00 hours like it is in your time string then...
$date = "2011-07-26 20:05:00";
$date = strtotime($date);
echo date('H', $date);
I'm not that familiar with PHP's date formats so you'll have to reference PHP.net for the correct formatting character for that.

At php side you use date('H',strtotime($date));
and at mysql side you can use DATE_FORMATE(NOW(),'%H') to get only hour
$date contains date like '2014/08/14' format
To convert date like '2014/08/14' to '14-08-2014' you have to use
date('d-m-Y',strtotime($date));
OR use
date('d-m-Y',strtotime(str_replace('/','-',$date)))

Best way to use DateTime class
$my_sql_date = "2011-07-26 20:05:00";
$date_time_obj = new DateTime($my_sql_date);
echo $date_time_obj->format('H');

For 24-hour and 12-hour format, please check below code:
$date = "2011-07-26 20:05:00";
echo $hours = date('G', strtotime($date)); // In 24-hour format of an hour without leading zeros
echo '<br>';
echo $hours = date('g', strtotime($date)); // 12-hour format of an hour without leading zeros
// For current timestamp
echo $hours = date('G'); // In 24-hour format of an hour without leading zeros
echo '<br>';
echo $hours = date('g'); //12-hour format of an hour without leading zeros
For reference please check: http://php.net/manual/en/function.date.php

The date_parse function will return a fulfilled array of a sections of a datetime. use it like this:
$now = date(now()); // "2021-08-30 21:52:21"
$open = date_parse($now)['hour']; // 21

$pattern = '[0-9]{2}:[0-9]{2}';
preg_match('/'.$pattern.'/', '2011-07-26 20:05:00', $matches);
echo $matches[0];

As of CakePHP 4.0+ you have the FrozenTime utility class. Just import it.
In a controller:
use Cake\I18n\FrozenTime;
class ExampleController extends AppController {
public function getHour() {
$now = FrozenTime::now();
$hour = $now->hour;
$this->set(compact('hour'));
}
}
Then in your view:
<?= $hour ?>
It should output something like this (assuming it's currently 2:30 PM):
14

Related

/Date(1341788400000+0100)/ to DD/MM/YYYY HH:MM

I have several dates being outputted into variables. They are formatted as follows:
/Date(1341788400000+0100)/
How would I go about formatting them using PHP into:
DD/MM/YYYY HH:MM
Thanks!
I ended up using the following, as the initial format was in milliseconds:
$date = 1341788400000+0100;
$date = ( $date / 1000 );
$date = date("d/m/Y H:m", $date);
$date = 1341788400000+0100;
echo date("Y/m/d H:m",$date);
Unless the +0100 is the actual time of the day (01:00) ?
First, you parse it, e.g. using strtok() http://php.net/manual/en/function.strtok.php
Then parse it as a number.
$seconds = intval($a)
Then format it using
date("Y/m/d H:m", $seconds)`.

Getting time and date from timestamp with php

In my database I have a time stamp column...which reflects a format like this: 2012-04-02 02:57:54
However I would like to separate them up into $date and $time.
After some research through the php manual...I found that date(), date_format() and strtotime() are able to help me to separate them...(not sure if I am right)
But I am not very sure of how to code it out...
In my php file...the timestamp extracted would be $row['DATETIMEAPP'].
Will
$date = strtotime('d-m-Y',$row['DATETIMEAPP']);
$time = strtotime('Gi.s',$row['DATETIMEAPP']);
or
$date = date('d-m-Y',$row['DATETIMEAPP']);
work?
Can I use date() to get the time as well??
Thanks in advance
$timestamp = strtotime($row['DATETIMEAPP']);
gives you timestamp, which then you can use date to format:
$date = date('d-m-Y', $timestamp);
$time = date('Gi.s', $timestamp);
Alternatively
list($date, $time) = explode('|', date('d-m-Y|Gi.s', $timestamp));
If you dont want to change the format of date and time from the timestamp, you can use the explode function in php
$timestamp = "2012-04-02 02:57:54"
$datetime = explode(" ",$timestamp);
$date = $datetime[0];
$time = $datetime[1];
$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));
You can try this:
For Date:
$date = new DateTime($from_date);
$date = $date->format('d-m-Y');
For Time:
$time = new DateTime($from_date);
$time = $time->format('H:i:s');
$timestamp='2014-11-21 16:38:00';
list($date,$time)=explode(' ',$timestamp);
// just time
preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];
Works for me:
select DATE( FROM_UNIXTIME( columnname ) ) from tablename;
If you want to use the DateTime class, you can do so like this:
$timestamp = $row['DATETIMEAPP']; // String formatted as "2012-04-02 02:57:54"
// Create DateTime object from custom timestamp
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $timestamp);
$date = $dt->format('d-m-Y'); // String variable of just the date
$time = $dt->format('H:i:s'); // String variable of just the time
And if you're concerned about using DateTime over strtotime() or date(), I'd like to point you in the direction of this conversation on StackOverflow titled "DateTime class vs. native PHP date-functions."
Optionally you can use database function for date/time formatting. For example in MySQL query use:
SELECT DATE_FORMAT(DATETIMEAPP,'%d-%m-%Y') AS date, DATE_FORMT(DATETIMEAPP,'%H:%i:%s') AS time FROM yourtable
I think that over databases provides solutions for date formatting too

Convert day, full month, year and country to YYYY-MM-DD

I'm trying to convert the string 18 December 2009 (Sweden) to 2009-12-18 but I can't figure out how. So I asking you now: how can I do this?
Thanks in advance.
You can use strtotime():
<?php
$sdate = '18 December 2009';
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
If your problem is that the '(Sweden)' part is always present, you could just remove that part first:
<?php
$sdate = '18 December 2009 (Sweden)';
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
Or with added checking:
<?php
$sdate = $oImdb->getReleaseDate();
if ($sdate !== 'n/A') {
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
} else {
$d = 'n/a';
}
echo "$d\n"; // 2009-12-18
Or use sscanf():
<?php
$sdate = '18 December 2009 (Sweden)';
list($day, $month, $year) = sscanf($sdate, '%d %s %d');
$timestamp = strtotime("$day $month $year");
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
I am not sure what you are doing there, but judging from the error message you wrote in your comment to JM above, I'd say you are approaching the problem from the wrong end. Quoting:
Thanks! When I try the function with $oIMDB->getReleaseDate() I get following error messages:
Fatal error: Uncaught exception 'Exception' with message DateTime::__construct() [datetime.--construct]: Failed to parse time string (<time itemprop="datePublished" datetime="2009-12-18">18 December 2009</time>) …
In other words, your getReleaseDate returns an XML string that has an attribute datetime with the value you are trying to convert the element value to. So, there is no need to convert anything, because the converted value is already there. All you have to do is use SimpleXml or DOM and access that attribute value, e.g.
$time = simplexml_load_string($oIMDB->getReleaseDate());
echo $time['datetime'];
First use Explode etc to remove the country name an store the Date and Country Name in separate strings, and then use strtotime
strtotime("18 December 2009")
strtotime(<String Variable containing date>)
It returns a timestamp, you can then use it as you want. See this for reference
Then use Date to convert the timestamp to date in the format you want.
There is also the PHP 5 DateTime object, which will allow you to capture time zones and convert time zones if start using times in addition to the date.
<?php
$sdate = '18 December 2009 (Sweden)';
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$datetime = new DateTime($sdate, new DateTimeZone('UTC'));
echo $datetime->format('Y-m-d'); // 2009-12-18
The DateTime object will allow you to manipulate the date without any seconds arithmetic, which can be a reason to use DateTime instead of strtotime().
For example, this would add one month to your original date. Many benefits of the DateTime class.
$datetime->add(new DateInterval('P1M'));

Sending time with timezone from PHP to flash

I am trying to send the time to flash but set to the currently timezone. When you view the below even though the echo date, looks like its working the $time is the same. When i test in flash I get the extra hour added. Any help tips welcome on this one...
$format = "d/m/Y H:m:s";
$timezone = "Europe/Amsterdam";
date_default_timezone_set($timezone);
echo "<h1>Timezone ".$timezone."</h1>";
$date = date($format);
echo "<h3>Date: ".$date."<h3>";
$time = strtotime($date);
echo "<h3>Time: ".$time."<h3>";
$date2 = date($format, $time);
echo "<h3>Reverse: ".$date2."<h3>";
$timezone = "Europe/London";
date_default_timezone_set($timezone);
echo "<h1>Timezone ".$timezone."</h1>";
$date = date($format);
echo "<h3>Date: ".$date."<h3>";
$time = strtotime($date);
echo "<h3>Time: ".$time."<h3>";
$date2 = date($format, $time);
echo "<h3>Reverse: ".$date2."<h3>";
?>
Can't you use the PHP time() object for this? Pass this value:
time()."000" // note the trailing zeroes
Call that serverTime and pass it as a query string:
echo "myFlashFile.swf?serverTime=".time()."000";
Then in your Actionscript:
myDate = new Date();
myDate.setTime(serverTime);
Would some sort of mathematics solve the day? ie:
$time = date("U")+date("Z");
This would work for the timezone ahead, but not so good for behind

Date minus 1 year?

I've got a date in this format:
2009-01-01
How do I return the same date but 1 year earlier?
You can use strtotime:
$date = strtotime('2010-01-01 -1 year');
The strtotime function returns a unix timestamp, to get a formatted string you can use date:
echo date('Y-m-d', $date); // echoes '2009-01-01'
Use strtotime() function:
$time = strtotime("-1 year", time());
$date = date("Y-m-d", $time);
Using the DateTime object...
$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');
Or using now for today
$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');
an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));
this worked perfect.. hope this will help someone else too.. :)
On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));
After, only compare the the two dates.
Hope it could help someone.
// set your date here
$mydate = "2009-01-01";
/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));
// format and display the computed date
echo date("Y-m-d", $lastyear);
Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval to modify a \Datetime object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Which returns:
2008-01-01
For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php
You can use the following function to subtract 1 or any years from a date.
function yearstodate($years) {
$now = date("Y-m-d");
$now = explode('-', $now);
$year = $now[0];
$month = $now[1];
$day = $now[2];
$converted_year = $year - $years;
echo $now = $converted_year."-".$month."-".$day;
}
$number_to_subtract = "1";
echo yearstodate($number_to_subtract);
And looking at above examples you can also use the following
$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));

Categories