This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I have a time as 5:4 pm and i want convert the time from AM/PM to 24 hour format in PHP, i try as date('H:i',strtotime('5:4 pm')) but this don't work and result is 16:00 in the event that it should be 17:04. what do i do?
DEMO: http://sandbox.onlinephpfunctions.com/code/bfd524f65ea4fa3031e55c9879aab711f31e1b37
I can not change this time.
I recommend PHP OOP way as they are always better than any procedural way(like using strtotime):
$time = '5:04 pm';
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');//17:04
Please mind that you need to provide : 5:04 pm , you CAN NOT use 5:4 pm .
Reason is that no date format exist for minutes without a leading zero.
For reference see this:
http://php.net/manual/en/datetime.createfromformat.php
If you have to have time in that format then you will need to manipulate it after you receive your time as follows:
$time = '5:4 pm';//works for formats -> '5:4 pm' gives 17:04,'5:40 pm' gives 17:40
$time2 = str_replace(' ',':',$time);
$time3 = explode(':',$time2);
if(((int)$time3[1])<10)//check if minutes as over 10 or under 10 and change $time accordingly
$time = $time3[0].':0'.$time3[1].' '.$time3[2];
else
$time = $time3[0].':'.$time3[1].' '.$time3[2];
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');
I hope it helps
Assuming the time string format will be same -
$time = explode(' ', '5:4 pm');
$temp = date_parse($time[0]);
$temp['minute'] = str_pad($temp['minute'], 2, '0', STR_PAD_LEFT);
echo date('H:i a', strtotime($temp['hour'] . ':' . $temp['minute'] . ' ' . $time[1]));
Output
17:04 pm
You should pass 5:04 pm instead of 5:4 pm, it seems the parameter expects 2 digits for the minute format.
Working example: http://sandbox.onlinephpfunctions.com/code/ecf968c844da50e8a9eec2dc85656f49d7d20dee
You can try this
echo date("H:i", strtotime("05:04 PM"));
Try to capitalize AM/PM
date('H:i', strtotime('5:04 PM'))
{EDIT}
Replace pm with PM using str_replace
echo date('H:i', strtotime(str_replace("pm","PM",'5:04 PM')))
Here is the code,
$time = '5:4 pm';
$arr = explode(" ",$time);
$arr1 = explode(":",$arr[0]);
foreach($arr1 as $k => $val){
$arr1[$k] = sprintf("%02d", $val);
}
$str = implode(":", $arr1)." ".$arr[1];
echo date('H:i',strtotime($str));
pure date wont work, so I am exploding it as it is special case
I hope this will work.
Thanks :)
// 24 hours format
$date = date("H:i a",time());
// just pass time() function instead of strtotime()
echo $date;
// output
// 17:04 pm
// to run a test, do reset your system time back or forward to 5:4 pm
Thanks, hope this helps.
Related
This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 5 years ago.
I would like to convert a date that comes in the format 06.11.2017 um 18:30 - 21:30 Uhr into the format 2017-11-06. So everything should be cut off after 06.11.2017 and the remaining date should be output in the format YYYY-MM-DD.
Is there an elegant way to do that?
$date = "06.11.2017 um 18:30 - 21:30 Uhr";
$date = explode(" ",$date);
if(array_key_exists(0,$date))
echo date("Y-m-d", strtotime($date[0]));
output: 2017-11-06
Explode the string
Convert the first part to the desired format.
Not elegant but easy to implement :
function formatDate($date) {
$date = explode(' ', $date);
$date = explode('.', $date[0]);
return $date[2] .'-'. $date[1] .'-'. $date[0];
}
echo formatDate('06.11.2017 um 18:30 - 21:30 Uhr');
You can do it by using Explode function of PHP to cut the unwanted date and then change its format.
Below PHP code can help:
<?php
$date = "06.11.2017 um 18:30 - 21:30 Uhr";
$dateArr = explode(" ",$date);
$wantedDate = $dateArr[0];
$newDate = date("Y-m-d", strtotime($wantedDate));
echo $newDate;
// Output will be 2017-11-06
?>
Assuming your date string is always on that format, use substr() to cut the string then format the date to 'Y-m-d'
$date = '06.11.2017 um 18:30 - 21:30 Uhr';
$date = substr($date, 0, 10); // cut string to take date
$date = new DateTime($date); // set string as datetime object
echo $date->format('Y-m-d'); // formatted date (2017-11-06)
How would you convert time to integer?
string(8) "04:04:07"
I want this as 4(hours) or much better 4.04(4hours and 4 minutes)
I tried
$yourdatetime = "04:04:07";
$timestamp = strtotime($yourdatetime);
Which results in
int(1458590887)
The date function is your friend:
Given your own code above:
$yourdatetime = "04:04:07";
$timestamp = strtotime($yourdatetime);
You can then feed it into the date function:
echo 'Hours:' . date('h', $timestamp); // Hours: 04
echo 'Minutes:' . date('i', $timestamp); // Minutes: 04
echo 'Seconds:' . date('s', $timestamp); // Seconds: 07
Refer to the docs for the specific format(s) you'd like for hours - there's many options.
You could even do it in one move:
echo date('h.i', $timestamp); // 04.04
If you need it truly numeric:
echo float(date('h.i', $timestamp)); // 4.04
Use (float) and preg_replace to one-line-code conversion:
$floatval = (float) preg_replace('/^(\d+):(\d+).+/','\1.\2',$yourdatetime);
So we'll break this out. If we cast the hours as an integer and leave the minutes as a string this is a pretty simple conversion
$time = explode(':', $yourdatetime);
$hours = (int)$time[0] . '.' . $time[1];
Avoids any overhead from regex
strtotime() returns the time in seconds since the Unix Epoch. You can then format this using date(). Documentation for date: http://php.net/manual/en/function.date.php
To get the number of hours (4):
$timestamp = date("g",strtotime($yourdatetime));
To get the number of hours and minutes (4.03):
$timestamp = date("g.i",strtotime($yourdatetime));
I'm trying to get the date from the week number, day number and year.
For eg:
week number = 52
day number = 4 (of week 52)
year = 2013
In this case, the date should be 26-12-2013.
How can I do it using PHP? I've already tried with strtotime(), but I'm confused about the formats. Can someone help?
Make use of setISODate()
<?php
$gendate = new DateTime();
$gendate->setISODate(2013,52,4); //year , week num , day
echo $gendate->format('d-m-Y'); //"prints" 26-12-2013
Try this code.
<?php
function change_date($week_num, $day) {
$timestamp = strtotime(date('Y') . '-W' . $week_num . '-' . $day);
return $timestamp;
}
$timestamp = change_date(52, 4);
echo date('d-m-Y', $timestamp);
?>
You can also use the strtotime function. In your example, you can write:
date("Y-m-d", strtotime("Y2013W52-4")) // outputs: 2013-12-26
The strtotime will give you a timestamp that you can use in combination withe the date function.
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
can anyone get me a code for hiding the time stamp from a string.
I used this code to get the date from the string
suppose the
$date_string = "02/06/2011 11:00 am - 2:00 pm";
$date = strtotime($date_string);
$date = date('m/d/y', $date);
But the out put I am getting is something like this
1/1/70
Please suggest a better way that I could implement for this to work
I want it to show like
02/06/2011
If the date you're looking for is already in the string and all you want to do is remove the time range, you don't need any date manipulation. Just remove everything after the space (assuming the format of the date_string remains consistent).
$date_string = "02/06/2011 11:00 am - 2:00 pm";
$date = explode(" ",$date_string);
echo $date[0];
Or even simpler (but untested)
echo strtok($date_string," "); //http://codepad.org/Or1mpYOp
PHP.NET:strtok
PHP.NET:explode
$date = strtotime($date_string);
$date = getdate($date);
$date = $date['mon'] . '/' . $date['mday'] . '/' . $date['year']
If 02/06/2011 11:00 am - 2:00 pm is what gets displayes, you're obviously displaying $date_string and not $date, because strtotime('02/06/2011 11:00 am - 2:00 pm'); returns boolean false, which date('m/d/y', $date) would convert to 01/01/1970.
Try something like this
$date_string = "02/06/2011 11:00 am - 2:00 pm";
$date_exploded = explode('-',$date_string);
$date = strtotime($date_exploded[0]);
$date = date('m/d/y', $date);
echo $date;
Leaving aside the fact that something is going very wrong in the date parsing, you need to be aware that using a date format of 00/00/00[00] is rather ambigious - in the US dates written like this are in the format mm/dd/yy[yy] while in the UK it is interpreted as dd/mm/yy[yy]. The strtotime function does not use the locale setting to work out which applies and always assumes the former.
If I were being asked to parse this, I'd go with using preg to extract the date part. Using a pattern:
/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2,4})/
gives an array
0=> 02/06/2011
1=> 02
2=> 06
3=> 2011
Then use mktime to generate the unix timstamp.
Other approaches include using substr to extract a fixed length string, or exploide by space to get words.
If your string is already is date .
$date = substr($records[$datetime, 0, 10);