What am I doing wrong in this Php coding? - php

Given a birthdate in the form mm/dd/yyyy, write a function that returns the person's age and true or false if today is the person's birthday.
For example, since today is 01/23/2015, your function would return the following:
getBirthDate('02/26/1975'); // returns array('age' => 39, 'birthday' => false);
getBirthDate('01/23/1994'); // returns array('age' => 21, 'birthday' => true);
This is what I have and I just cant seem to find out why the output wont come out like I need it to. When I run this code, no output is shown, but I can't figure out what I did wrong. What I want it to do is when it is run, it should output the age and true or false if that date is the person's birthday. But whenever I run this piece of code, the output is always blank or it just says Array. I would appreciate any help or suggestions to solving this! Thanks!
<?php
function getBirthDate($birthdate)
{
$agebirthday = array();
list($D, $M, $Y) = explode("/", $birthdate);
$YearDifference = date("y") - $Y;
if (date("m") == $M && (date("d") == $D))
{
$Birthday = true;
}
else {
$Birthday = false;
}
array_push($agebirthday, array(
"age" => $YearDifference,
"birthday" => $Birthday));
return $agebirthday;
}
$output = getBirthDate($birthdate);
echo $output['age'];
echo $output['birthday'];
?>

Here's my version, I've changed a few things:
function getBirthDate($birthdate)
{
list($D, $M, $Y) = explode('/', $birthdate);
$YDiff = date('Y') - $Y;
// the line below is optional, you may wish to count complete years age or not
if(date("md") < $M.$D) $YDiff --; // if it's BEFORE birthday
return [
"age" => $YDiff,
"birthday" => date('md') == $M.$D
];
}
$output = getBirthDate('28/05/1981');
var_dump($output['age']);
var_dump($output['birthday']);
Gives us the correct answer, for my birthday:
int(33)
bool(false)

Make use of the strtotime() function. It converts dates to a large integer representing the number of seconds elapsed between the year 1970 and the date you specify, then subtract the value from the value of the time() function to get the number of seconds of time difference. Then use division on the result to get the desired number.
For example:
$seconds_old=time()-strtotime("02/26/1975");
Then you can do this:
$minutes_old=$seconds_old / 60;
$hours_old=$minutes_old / 60;
$days_old=$hours_old / 24;
$years_old=$days_old / 365;
And if the precision is too high, then research the intval() function.

in your code , change
array_push($agenbirthday, array(
"age" => $YDiff,
"birthday" => $Birthday));
to
$agenbirthday = array(
"age" => $YDiff,
"birthday" => $Birthday);

Related

How to subtract time from time array using php?

Hello seniors I have a question related to some PHP script.
I have an array containing time => ['12:10', '4:16', '2:5'] and have one html form containing input field of type 'number'.
I want when I enter some value in my form input field for example I enter 7, so after submitting the form in back-end the number 7 which i enter in input field is subtracted from the array which I mentioned above and I will get the result array like:
['5:10', '4:16', '2:5']
I have tried something like that but not able to implement my logic
$val = array(1, 0, 2, 1, 1);
$subtract = 3.5;
foreach ($val as $key => $item) {
if ($subtract >= $item) {
$subtract -= $item;
$val[$key] = 0;
} else {
$val[$key] -= $subtract;
$subtract = 0;
}
}
Any kind of help is highly appreciated
You can use Carbon library for date/time manipulation:
<?php
use Carbon\Carbon;
$times = ['17:46', '03:05', '21:56'];
$timeshift = 3;
$new_times = array_map(
fn($t) => Carbon::createFromFormat('H:i', $t)
->subHours($timeshift)
->format('H:i'),
$times
);
Test Carbon library online
No need for library, just convert your first array to seconds: 1 hour = 3600 ; 1 minute = 60 ; 12:10 is 12 x 3600 + 10 x 60, then you do the same thing to your $_POST value, then use gmdate() to retrieve the original format of your array
$myTimes=array('12:10', '4:16', '2:5');
//do the math
$splittedTime = explode(":", $myTimes[0]); //in your case
$timeInSeconds = $splittedTime[0] * 3600 + $splittedTime[1] * 60 ;
//do the same thing to your your $_POST value if needed or simply
$totalReduceby = 7 * 3600;
// get new total of seconds
$newTime= $timeInSeconds - $totalReduceby;
$result = ltrim(gmdate("H:i", $newTime),0); //ltrim to remove the leading 0
$myTimes=array($result, '4:16', '2:5');
//print_r($myTimes);
time => ['12:10', '4:16', '2:5']
[...]
the number 7 which i enter in input field is subtracted from the array
I will get the result array like: ['5:10', '4:16', '2:5']
Your example is a little ambiguous. Do you only want to subtract the field value from the first element of the array, always? Or only from those elements which are greater than the submitted value?
It's pretty straightforward to subtract minutes from a mm:ss time string; simplest is probably to generalize so that the amount to subtract is also allowed to be mm:ss instead of always being a whole number of minutes. I would just explode both of them, turn them into total seconds (minutes*60+seconds), subtract those, and then turn back into mm:ss. Both conversions might be worth their own functions:
function mmssToSeconds($timeStr) {
if (str_contains($timeStr, ':')) {
list($min, $sec) = explode(':', $timeStr);
} else {
list($min, $sec) = array($timeStr, 0);
}
if ($min < 0) {
return 60*$min - $sec;
} else {
return 60*$min + $sec;
}
}
function secondsToMmss($seconds) {
$abs = abs($seconds);
$sgn = $seconds / $abs;
$min = floor($abs / 60);
$sec = $abs % 60;
return ($sgn < 0 ? '-' : '').sprintf('%d:%02d', $min, $sec);
}
And then the subtraction is easy:
function subtractMinutes($from, $delta) {
return secondsToMmss(mmssToSeconds($from) - mmssToSeconds($delta));
}
If you want to subtract from each element that is big enough, you could use a loop like this:
foreach ($ary['time'] as $i => $t) {
if ((int)$t > $subtract) {
$ary['time'][$i] = subtractMinutes($t, $subtract);
}
}
The comparison works because the cast from string to int ignores everything after the first non-digit, so '12:10' just becomes 12, which is > 7.

Ranking with Echo on Php [duplicate]

I want to display numbers as follows
1 as 1st,
2 as 2nd,
...,
150 as 150th.
How should I find the correct ordinal suffix (st, nd, rd or th) for each number in my code?
from wikipedia:
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
$abbreviation = $number. 'th';
else
$abbreviation = $number. $ends[$number % 10];
Where $number is the number you want to write. Works with any natural number.
As a function:
function ordinal($number) {
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if ((($number % 100) >= 11) && (($number%100) <= 13))
return $number. 'th';
else
return $number. $ends[$number % 10];
}
//Example Usage
echo ordinal(100);
PHP has built-in functionality for this. It even handles internationalization!
$locale = 'en_US';
$nf = new NumberFormatter($locale, NumberFormatter::ORDINAL);
echo $nf->format($number);
Note that this functionality is only available in PHP 5.3.0 and later.
This can be accomplished in a single line by leveraging similar functionality in PHP's built-in date/time functions. I humbly submit:
Solution:
function ordinalSuffix( $n )
{
return date('S',mktime(1,1,1,1,( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
}
Detailed Explanation:
The built-in date() function has suffix logic for handling nth-day-of-the-month calculations. The suffix is returned when S is given in the format string:
date( 'S' , ? );
Since date() requires a timestamp (for ? above), we'll pass our integer $n as the day parameter to mktime() and use dummy values of 1 for the hour, minute, second, and month:
date( 'S' , mktime( 1 , 1 , 1 , 1 , $n ) );
This actually fails gracefully on values out of range for a day of the month (i.e. $n > 31) but we can add some simple inline logic to cap $n at 29:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20))*10 + $n%10) ));
The only positive value(May 2017) this fails on is $n == 0, but that's easily fixed by adding 10 in that special case:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n>=20)+($n==0))*10 + $n%10) ));
Update, May 2017
As observed by #donatJ, the above fails above 100 (e.g. "111st"), since the >=20 checks are always returning true. To reset these every century, we add a filter to the comparison:
date( 'S', mktime( 1, 1, 1, 1, ( (($n>=10)+($n%100>=20)+($n==0))*10 + $n%10) ));
Just wrap it in a function for convenience and off you go!
Here is a one-liner:
$a = <yournumber>;
echo $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
Probably the shortest solution. Can of course be wrapped by a function:
function ordinal($a) {
// return English ordinal number
return $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
}
Regards,
Paul
EDIT1: Correction of code for 11 through 13.
EDIT2: Correction of code for 111, 211, ...
EDIT3: Now it works correctly also for multiples of 10.
from http://www.phpro.org/examples/Ordinal-Suffix.html
<?php
/**
*
* #return number with ordinal suffix
*
* #param int $number
*
* #param int $ss Turn super script on/off
*
* #return string
*
*/
function ordinalSuffix($number, $ss=0)
{
/*** check for 11, 12, 13 ***/
if ($number % 100 > 10 && $number %100 < 14)
{
$os = 'th';
}
/*** check if number is zero ***/
elseif($number == 0)
{
$os = '';
}
else
{
/*** get the last digit ***/
$last = substr($number, -1, 1);
switch($last)
{
case "1":
$os = 'st';
break;
case "2":
$os = 'nd';
break;
case "3":
$os = 'rd';
break;
default:
$os = 'th';
}
}
/*** add super script ***/
$os = $ss==0 ? $os : '<sup>'.$os.'</sup>';
/*** return ***/
return $number.$os;
}
?>
Simple and Easy Answer will be:
$Day = 3;
echo date("S", mktime(0, 0, 0, 0, $Day, 0));
//OUTPUT - rd
I wrote this for PHP4.
It's been working ok & it's pretty economical.
function getOrdinalSuffix($number) {
$number = abs($number) % 100;
$lastChar = substr($number, -1, 1);
switch ($lastChar) {
case '1' : return ($number == '11') ? 'th' : 'st';
case '2' : return ($number == '12') ? 'th' : 'nd';
case '3' : return ($number == '13') ? 'th' : 'rd';
}
return 'th';
}
you just need to apply given function.
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
Generically, you can use that and call echo get_placing_string(100);
<?php
function get_placing_string($placing){
$i=intval($placing%10);
$place=substr($placing,-2); //For 11,12,13 places
if($i==1 && $place!='11'){
return $placing.'st';
}
else if($i==2 && $place!='12'){
return $placing.'nd';
}
else if($i==3 && $place!='13'){
return $placing.'rd';
}
return $placing.'th';
}
?>
I made a function that does not rely on the PHP's date(); function as it's not necessary, but also made it as compact and as short as I think is currently possible.
The code: (121 bytes total)
function ordinal($i) { // PHP 5.2 and later
return($i.(($j=abs($i)%100)>10&&$j<14?'th':(($j%=10)>0&&$j<4?['st', 'nd', 'rd'][$j-1]:'th')));
}
More compact code below.
It works as follows:
printf("The %s hour.\n", ordinal(0)); // The 0th hour.
printf("The %s ossicle.\n", ordinal(1)); // The 1st ossicle.
printf("The %s cat.\n", ordinal(12)); // The 12th cat.
printf("The %s item.\n", ordinal(-23)); // The -23rd item.
Stuff to know about this function:
It deals with negative integers the same as positive integers and keeps the sign.
It returns 11th, 12th, 13th, 811th, 812th, 813th, etc. for the -teen numbers as expected.
It does not check decimals, but will leave them in place (use floor($i), round($i), or ceil($i) at the beginning of the final return statement).
You could also add format_number($i) at the beginning of the final return statement to get a comma-separated integer (if you're displaying thousands, millions, etc.).
You could just remove the $i from the beginning of the return statement if you only want to return the ordinal suffix without what you input.
This function works commencing PHP 5.2 released November 2006 purely because of the short array syntax. If you have a version before this, then please upgrade because you're nearly a decade out of date! Failing that, just replace the in-line ['st', 'nd', 'rd'] with a temporary variable containing array('st', 'nd', 'rd');.
The same function (without returning the input), but an exploded view of my short function for better understanding:
function ordinal($i) {
$j = abs($i); // make negatives into positives
$j = $j%100; // modulo 100; deal only with ones and tens; 0 through 99
if($j>10 && $j<14) // if $j is over 10, but below 14 (so we deal with 11 to 13)
return('th'); // always return 'th' for 11th, 13th, 62912th, etc.
$j = $j%10; // modulo 10; deal only with ones; 0 through 9
if($j==1) // 1st, 21st, 31st, 971st
return('st');
if($j==2) // 2nd, 22nd, 32nd, 582nd
return('nd'); //
if($j==3) // 3rd, 23rd, 33rd, 253rd
return('rd');
return('th'); // everything else will suffixed with 'th' including 0th
}
Code Update:
Here's a modified version that is 14 whole bytes shorter (107 bytes total):
function ordinal($i) {
return $i.(($j=abs($i)%100)>10&&$j<14?'th':#['th','st','nd','rd'][$j%10]?:'th');
}
Or for as short as possible being 25 bytes shorter (96 bytes total):
function o($i){return $i.(($j=abs($i)%100)>10&&$j<14?'th':#['th','st','nd','rd'][$j%10]?:'th');}
With this last function, simply call o(121); and it'll do exactly the same as the other functions I listed.
Code Update #2:
Ben and I worked together and cut it down by 38 bytes (83 bytes total):
function o($i){return$i.#(($j=abs($i)%100)>10&&$j<14?th:[th,st,nd,rd][$j%10]?:th);}
We don't think it can possibly get any shorter than this! Willing to be proven wrong, however. :)
Hope you all enjoy.
An even shorter version for dates in the month (up to 31) instead of using mktime() and not requiring pecl intl:
function ordinal($n) {
return (new DateTime('Jan '.$n))->format('jS');
}
or procedurally:
echo date_format(date_create('Jan '.$n), 'jS');
This works of course because the default month I picked (January) has 31 days.
Interestingly enough if you try it with February (or another month without 31 days), it restarts before the end:
...clip...
31st
1st
2nd
3rd
so you could count up to this month's days with the date specifier t in your loop: number of days in the month.
function ordinal($number){
$last=substr($number,-1);
if( $last>3 || $last==0 || ( $number >= 11 && $number <= 19 ) ){
$ext='th';
}else if( $last==3 ){
$ext='rd';
}else if( $last==2 ){
$ext='nd';
}else{
$ext='st';
}
return $number.$ext;
}
Here is the correct solution
$numberFormatter = new NumberFormatter('en_US', NumberFormatter::ORDINAL);
echo $numberFormatter->format(11);
Found an answer in PHP.net
<?php
function ordinal($num)
{
// Special case "teenth"
if ( ($num / 10) % 10 != 1 )
{
// Handle 1st, 2nd, 3rd
switch( $num % 10 )
{
case 1: return $num . 'st';
case 2: return $num . 'nd';
case 3: return $num . 'rd';
}
}
// Everything else is "nth"
return $num . 'th';
}
?>
Here's another very short version using the date functions. It works for any number (not constrained by days of the month) and takes into account that *11th *12th *13th does not follow the *1st *2nd *3rd format.
function getOrdinal($n)
{
return $n . date_format(date_create('Jan ' . ($n % 100 < 20 ? $n % 20 : $n % 10)), 'S');
}
I realise this is an ancient post, however it's probably worth adding that as of PHP 8, the match control structure allows a more concise:
$ordinal = match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };
If you need to append that to the position to get a place:
$place = $position.match(in_array(abs($position)%100, [11, 12, 13]) ? 0 : abs($position)%10) { 1 => 'st', 2 => 'nd', 3 => 'rd', default => 'th' };
You can obviously simplify that out if you know your position will always be positive or less than 11 or whatever.
I fond this small snippet
<?php
function addOrdinalNumberSuffix($num) {
if (!in_array(($num % 100),array(11,12,13))){
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1: return $num.'st';
case 2: return $num.'nd';
case 3: return $num.'rd';
}
}
return $num.'th';
}
?>
HERE

Getting the average of an array of dates differences using PHP

I'm trying to get the average time a user spends on my site using my own built analytics.
I'm using the DateTime class right now but the math seems very sketchy. Say I have an array of login times and logout times.
$array = array(
array("login" => '2012-01-31 10:35:58', "logout" => '2012-02-01 10:35:58'),
array("login" => '2012-02-04 10:35:58', "logout" => '2012-02-05 10:35:58')
);
I want to get the of amount of time between each login and logout, then find the average of all those times.
$total = 0;
$count = 0;
foreach ($array as $timestamp) {
$diff = strtotime($timestamp['logout']) - strtotime($timestamp['login']);
$total += $diff;
$count++;
}
echo "Average session time is ", $total / $count;
For safety's sake, you'd be better off using DateTime::createFromFormat() to do the date->time parsing. Your timestamps are a nice normal format, but strtotime is unreliable when you've got some wonky formats.
As well, this code assumes that all login/logout pairs are fully defined. If you have any where either time is off, you'll end up with some huge outliers as those'll most likely come out as 0, rather than a normal "modern" timestamp.
You could do something like:
$sessions = array();
foreach($array as $s) {
$sessions[] = strtotime($s['logout']) - strtotime($s['login']);
}
Now $sessions is an array of all the session lengths in seconds, so if you then do:
$average = array_sum($sessions) / count($sessions);
That is the average session length, in seconds. You could then print that in human-readable format, but I think that's beyond the scope of this question.
The reason I am putting the session lengths in an array first instead of simply summing them up in the loop is that you can then also get other statistics out of it, like longest/shortest sessions, median, etc.
Example using DateTime (tested).
define('DATETIME_FORMAT', 'Y-m-d H:i:s');
$array = array(
array('login' => '2012-01-31 10:35:58', 'logout' => '2012-02-01 10:35:58'),
array('login' => '2012-02-04 10:35:58', 'logout' => '2012-02-06 10:22:58')
);
$total = 0;
$count = 0;
foreach($array as $timeInfo)
{
$loginDatetime = DateTime::createFromFormat(DATETIME_FORMAT, $timeInfo['login']);
$logoutDatetime = DateTime::createFromFormat(DATETIME_FORMAT, $timeInfo['logout']);
$total += ($logoutDatetime->getTimestamp() - $loginDatetime->getTimestamp());
$count++;
}
$average = $total / $count;
echo "Average session duration: ".$average." seconds";
EDIT: initally I've used an array to store diffs, ending with array_sum() / count() to compute the average, but I found Marc B's solution with $total and $count simpler and certainly faster (it may matter here since potentially a lot of login/logout datetimes will be processed). => applied it here.
$array = array( array ("login" => "2012-01-31 10:35:58", "logout" => "2012-02-01 10:35:58"),
array ("login" => "2012-02-04 10:35:58", "logout" => "2012-02-05 10:35:58") );
$amount = 0 ;
foreach( $array as $at )
{
$amount += strtotime( $at[ "logout" ] ) - strtotime( $at[ "login" ] ) ;
}
$average = $amount / count( $array ) ;
echo "amount: $amount seconds\naverage $average seconds\n" ;

Translating a PHP function that converts seconds to human readable string

In this website I've found a function to convert seconds in an human readable format, like this:
3 weeks, 2 days, 1 hour, 27 minutes, 52 seconds
I want to translate it in italian, so I just translated array keys. The function now is this
function secondsToHumanReadable($secs) {
$units = array(
'settimane' => 604800,
'giorni' => 86400,
'ore' => 3600,
'minuti' => 60,
'secondi' => 1
);
foreach ( $units as &$unit ) {
$quot = intval($secs / $unit);
$secs -= $quot * $unit;
$unit = $quot;
}
return $units;
}
It works pretty well, but there's a little problem: in english all the plurals ends with one letter less, but unfortunately in italian it's not the same, as you can see below.
English Italian
- weeks, week - settimane, settimana
- days, day - giorni, giorno
- hours, hour - ore, ora
- minutes, minute - minuti, minuto
- seconds, second - secondi, secondo
I want to find a solution to print singular keys when the values are == 1.
I was thinking that I could merge the array with another array that have singular keys, using array_combine().
$singular_units = array(
'settimana',
'giorno',
'ora',
'minuto',
'secondo'
);
print_r(array_combine( $singular_units, $units ));
/* print_r:
Array
(
[settimana] => 604800
[giorno] => 86400
[ora] => 3600
[minuto] => 60
[secondo] => 1
)
*/
The array above is what I need, but I'm not able to use it, since I just cannot use another foreach.
$seconds = 12345*60; // just an example
$units = secondsToHumanReadable($seconds);
$time_string = '';
foreach ($units as $u => $v)
if (!empty($v))
$time_string.= $v.' '.$u.', ';
echo substr($time_string, 0, -2);
// 1 settimane, 1 giorni, 13 ore, 45 minuti
// this echo is not correct :( is expected to be like this:
// 1 settimana, 1 giorno, 13 ore, 45 minuti
How could I implement the singular words?
Any help is really appreciated! Thank you so much in advance!
You can implement them any way you like, IMHO preferably something not like the current solution which lacks clarity and readability (at least that's how the local-var-mutation-with-refs-and-variable-ping-pong looks like to me).
Just one possible solution:
$input = 12345 * 60;
$units = array(
604800 => array('settimana', 'settimane'),
86400 => array('giorno', 'giorni'),
// etc
);
$result = array();
foreach($units as $divisor => $unitName) {
$units = intval($input / $divisor);
if ($units) {
$input %= $divisor;
$name = $units == 1 ? $unitName[0] : $unitName[1];
$result[] = "$units $name";
}
}
echo implode(', ', $result);
See it in action.
Your probably want something like this?
function secondsToHumanReadable($secs) {
$units = array(
'settimane' => 604800,
'giorni' => 86400,
'ore' => 3600,
'minuti' => 60,
'secondi' => 1
);
foreach ( $units as $key => &$unit ) {
$this_unit = intval($secs / $unit);
$secs -= $this_unit * $unit;
if($this_unit == 1):
switch($key):
case "settimane":
$this_key = "settimana";
break;
case "giorni":
$this_key = "giorno";
break;
case "ore":
$this_key = "ora";
break;
case "minuti":
$this_key = "minuto";
break;
case "secondi":
$this_key = "secondo";
break;
endswitch;
else:
$this_key = $key;
endif;
$results[$this_key] = $this_unit;
}
return $results;
}
This will return the full array, not your initial one...with results...
Was also going to mention that some frameworks have Inflector classes which will determine the plural/singular version of a word, however I am not sure if they support languages such as Italian, but it may be worth a look. Personally I use CakePHP Inflector as it is a stand alone lib and I didn't need to bring in any other files.
CakePHP Inflector class
http://api.cakephp.org/class/inflector
Doctrine Inflector: http://www.doctrine-project.org/api/common/2.0/doctrine/common/util/inflector.html

PHP date(): minutes without leading zeros

I'd like to know if there is a formatting letter for PHP's date() that allows me to print minutes without leading zeros, or whether I have to manually test for and remove leading zeros?
Use:
$minutes = intval(date('i'));
For times with more information than just minutes:
ltrim() - Strip whitespace (or other characters) from the beginning of a string
ltrim(date('i:s'), 0);
returns:
8:24
According to the PHP Documentation, the date() function does not have a placeholder for minutes without leading zeros.
You could, however, get that information by simply multiplying the dates, with a leading zero, by 1, turning it into an integer.
$minutesWithoutZero = 1* date( 'i' );
I tried to find this for seconds as well, gave up the search and just casting the result as a int like this:
echo (int)date("s");
That will get rid of the leading zero's in a fast efficient way.
Doesn't look like it, but you could do something like...
echo date('g:') . ltrim(date('i'), '0');
Alternately, you could cast the second call to date() with (int).
This also works
$timestamp = time(); // Or Your timestamp. Skip passing $timestamp if you want current time
echo (int)date('i',$timestamp);
I use this format if I need a XXmXXs format:
//Trim leading 0's and the 'm' if no minutes
ltrim(ltrim(gmdate("i\ms\s", $seconds), '0'), 'm');
This will output the following:
12m34s
1m23s
12s
i just did this one line solution
$min = intval(date('i',strtotime($date)));
Using ltrim method may remove all the leading zeroes.For ex if '00' min.In this case this will remove all the zeroes and gives you empty result.
My solution:
function seconds2string($seconds) {
if ($seconds == 0) {
return '-';
}
if ($seconds < 60) {
return date('0:s', $seconds);
}
if ($seconds < 3600) {
return ltrim(date('i:s', $seconds), 0);
}
return date('G:i:s', $seconds);
}
This will output:
0 seconds: -
10 seconds: 0:10
90 seconds: 1:30
301 seconds: 5:01
1804 seconds: 30:04
3601 seconds: 1:00:01
Just use this:
(int) date('i');
Or in mySQL just multiply it by 1, like such:
select f1, ..., date_format( fldTime , '%i' ) * 1 as myTime, ..., ...
$current_date = Date("n-j-Y");
echo $current_date;
// Result m-d-yy
9-10-2012
A quickie from me. Tell me what you think:
<?php function _wo_leading_zero($n) {
if(!isset($n[1])) return $n;
if(strpos($n, '.') !== false) {
$np = explode('.', $n); $nd = '.';
}
if(strpos($n, ',') !== false) {
if(isset($np)) return false;
$np = explode(',', $n); $nd = ',';
}
if(isset($np) && count($np) > 2) return false;
$n = isset($np) ? $np[0] : $n;
$nn = ltrim($n, '0');
if($nn == '') $nn = '0';
return $nn.(isset($nd) ? $nd : '').(isset($np[1]) ? $np[1] : '');
}
echo '0 => '._wo_leading_zero('0').'<br/>'; // returns 0
echo '00 => '._wo_leading_zero('00').'<br/>'; // returns 0
echo '05 => '._wo_leading_zero('05').'<br/>'; // returns 5
echo '0009 => '._wo_leading_zero('0009').'<br/>'; //returns 9
echo '01 => '._wo_leading_zero('01').'<br/>'; //returns 1
echo '0000005567 => '._wo_leading_zero('0000005567').'<br/>'; //returns 5567
echo '000.5345453 => '._wo_leading_zero('000.5345453').'<br/>'; //returns 0.5345453
echo '000.5345453.2434 => '._wo_leading_zero('000.5345453.2434').'<br/>'; //returns false
echo '000.534,2434 => '._wo_leading_zero('000.534,2434').'<br/>'; //returns false
echo date('m').' => '._wo_leading_zero(date('m')).'<br/>';
echo date('s').' => '._wo_leading_zero(date('s')).'<br/>'; ?>
use PHP's absolute value function:
abs( '09' ); // result = 9
abs( date( 'i' ) ); // result = minutes without leading zero
My Suggestion is Read this beautiful documentation it have all details of php date functions
Link of Documentation
And as per your question you can use i - Minutes with leading zeros (00 to 59) Which return you minutes with leading zero(0).
And Also introducing [Intval()][2] function returns the integer value of a variable. You can not use the intval() function on an object

Categories