Posts

Showing posts from July, 2020

PHP: Calculate the percentage of a number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16   //My number is 928. $myNumber = 928 ;   //I want to get 25% of 928. $percentToGet = 25 ;   //Convert our percentage value into a decimal. $percentInDecimal = $percentToGet / 100 ;   //Get the result. $percent = $percentInDecimal * $myNumber ;   //Print it out - Result is 232. echo $percent ;

PHP Date: Time difference in days and years, months, days, hours, minutes, seconds between two dates

Write a PHP script to get time difference in days and years, months, days, hours, minutes, seconds between two dates. Note : Use DateTime class. Sample Solution: PHP Code: $date1 = new DateTime ( '2012-06-01 02:12:51' ) ; $date2 = $date1 - > diff ( new DateTime ( '2014-05-12 11:10:00' ) ) ; echo $date2 - > days . 'Total days' . "\n" ; echo $date2 - > y . ' years' . "\n" ; echo $date2 - > m . ' months' . "\n" ; echo $date2 - > d . ' days' . "\n" ; echo $date2 - > h . ' hours' . "\n" ; echo $date2 - > i . ' minutes' . "\n" ; echo $date2 - > s . ' seconds' . "\n" ; ?>

PHP Time Ago Function

Time Ago Function is a function that is commonly used to display time in human understandable format, as you have seen many times on social networks, whenever you post any status on your Facebook, Twitter or any other network, it says posted few seconds ago, 1 min ago, 1 hour age, etc. This is actually done by subtracting the current time from the post published time. //Creating Function function TimeAgo ( $oldTime , $newTime ) { $timeCalc = strtotime ( $newTime ) - strtotime ( $oldTime ) ; if ( $timeCalc >= ( 60 * 60 * 24 * 30 * 12 * 2 ) ) { $timeCalc = intval ( $timeCalc / 60 / 60 / 24 / 30 / 12 ) . " years ago" ; } else if ( $timeCalc >= ( 60 * 60 * 24 * 30 * 12 ) ) { $timeCalc = intval ( $timeCalc / 60 / 60 / 24 / 30 / 12 ) . " year ago" ; } else if ( $timeCalc >= ( 60 * 60 * 24 * 30 * 2 ) ) { $timeCalc = intval ( $timeCalc / 60 / 60 / 24 / 30 ) . " months ago" ; } else if ( $time