Checking hour and minutes inside datetime - php

Is there a way to see inside this function if $hours and $minutes are any other than 00:00, so that if they arent, i wont show the time?
public static function datetimedutch($date)
{
if ($date != '')
{
list($newdate, $time) = explode(' ', $date);
list($date_year, $date_month, $date_day) = explode('-', $newdate);
list($hours, $minutes, $seconds) = explode(':', $time);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maandnr = date("n", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maand_dag = date("j", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
}
}

This should do it :)
function datetimedutch($date)
{
if (!empty($date))
{
$someDate = strtotime($date);
$hours = date('H',$someDate);
$minutes = date('i',$someDate);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", $someDate);
$maandnr = date("n", $someDate);
$maand_dag = date("j", $someDate);
if($hours>0 || $minutes>0) {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
} else {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr];
}
} else {
return false;
}
}
echo datetimedutch('2014-05-15 12:39:06');
echo "<br />";
echo datetimedutch('2014-05-15 00:00:06');

I really recommend using automated way of getting locale formatted date, for example:
function formatDateInDutch($date = null) {
$date = strtotime($date);
$currentLocale = setlocale(LC_TIME, 0);
switch (PHP_OS){
case 'WIN':
case 'WINNT':
setlocale(LC_TIME, 'Dutch');
break;
case 'LINUX':
default:
setlocale(LC_TIME, 'nl_NL');
}
// format: http://pl1.php.net/manual/en/function.strftime.php
$ret = strftime('%A %w %B %m', $date);
// has minutes, display hour:minute
if ((int)date('i', $date) != 0) {
$ret .= ' '.date('H:i', $date);
// has only hours
} elseif ((int)date('H', $date) != 0 AND (int)date('i', $date) == 0) {
$ret .= ' '.date('H', $date);
}
// restore default locale
setlocale(LC_TIME, $currentLocale);
return $ret;
}
function formatDateInDutchBetter($date = null){
$date = new DateTime($date, new DateTimeZone('Europe/Amsterdam'));
// format: http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details
$formatPattern = 'EEEE e LLLL dd ';
// NOTE: $date->format and IntlDateFormatter format patterns ARE DIFFERENT!!!
// if datetime has minutes then display hour:minutes
if ((int)$date->format('i') != 0) {
$formatPattern .= 'HH:mm';
// if datetime has only minutes display minutes
} elseif ((int)$date->format('H') != 0 AND (int)$date->format('i') == 0) {
$formatPattern .= 'HH';
}
$formattedDate = IntlDateFormatter::formatObject($date, $formatPattern, 'nl_NL');
return $formattedDate;
}
print formatDateInDutch(date('Y-m-d H:m:s'));
print '<hr>';
print formatDateInDutchBetter(date('Y-m-d H:m:s'));
And I really recommend second approach: using internationalization extension from PHP. It requires enabling extension but it is platform independent and it is very easy to add/change other locales.

Related

Calculating and adjusting dates based on exceptions (PHP)

Here are the rules:
The adding of days is always by 15s (ex. 15, 30, 45, 60, etc.)
When the maturity date day falls on the 15th or end of the month
(ex. 30 or 31 depends on the month, 28 or 29 every February depends
if leap year) when adding days (as mention above) the date
should fall ONLY to 15th or end of month.
When the maturity date day does not fall every 15th or end of the
month just normally add days.
When the date is February 14 and add 15 days it should return 02/29 if leap year or 02/28 if not leap year.
Here is my code but, I am getting 1 error and inconsistency.
Catchable fatal error when the date is 02/29/2020 and add 30 days.
What can I do to accommodate this rules?
function adjustDate($maturitydate, $add) {
$nodays = '+'.$add.' days';
$date = new DateTime($maturitydate);
$matdt = $date->modify($nodays);
$ismaturitydateendofmonth = check_end_of_month($maturitydate);
if($date->format('d') == 15) {
$matdt = $matdt->format('m/15/Y');
}
else if($ismaturitydateendofmonth == '1'){
$matdt->modify('last day of this month');
}
else{
$matdt = $matdt->format('m/d/Y');
}
return $matdt;
}
function check_end_of_month($date){
//adds 1 day to date
$Temp = date('m/d/Y',strtotime("+1 day", strtotime($date)));
//get the month of each date
$tempmonth = date('m', strtotime($Temp));
$datemonth = date('m', strtotime($date));
//check if the months are equal
if($tempmonth != $datemonth){
return '1';
}
else{
return '0';
}
}
The code below will fix all the exceptions and inconsistencies.
$matdt = $maturitydatefrom;
for ($x = 0; $x < $chknumdif; $x++) {
$matdt = getNextDuedate($matdt, $maturitydatefrom);
}
function getNextDuedate($prevdate, $maturitydate){
$maturityday = date('d', strtotime($maturitydate));
$prevday = date('d', strtotime($prevdate));
$prevmonth = date('m', strtotime($prevdate));
$prevyear = date('Y', strtotime($prevdate));
$prevlastday = date('t', strtotime($prevdate));
$maturitylastday = date('t', strtotime($maturitydate));
$isendofmonth = check_end_of_month($maturitydate);
if($maturityday == $maturitylastday || $maturityday == 15){
if($prevday == 15){
$duedate = $prevmonth . '/' . $prevlastday . '/' . $prevyear;
}
else{
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/15/' . date('Y', strtotime($prevdate));
}
}
else{
if($prevday < 15){
if($prevmonth == '2' && $prevday == '14'){
$duedate = $prevmonth . '/' . $prevlastday . '/' . $prevyear;
}
else{
$duedate = $prevmonth . '/' . ($prevday + 15) . '/' . $prevyear;
}
}
else if($prevday > 15){
if($maturityday < 15){
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/' . $maturityday . '/' . date('Y', strtotime($prevdate));
}
else{
$prevdate = date('m/d/Y', strtotime("+1 month", strtotime($prevdate)));
$duedate = date('m', strtotime($prevdate)) . '/' . ($maturityday - 15) . '/' . date('Y', strtotime($prevdate));
}
}
}
return $duedate;
}

php - Calculate different from string

I have 2 string like this "2018/04/10-14:54:55" and "2018/04/10-14:56:10".
How can I calculate different between them? I've used strtotime to change the string to date but it gives the wrong value.
Please help me with this.
Thank you
<?php
$time1 = '2018/04/10-14:54:55';
$time2 = '2018/04/10-14:56:10';
$format = 'Y/m/d-H:i:s';
$t1 = DateTime::createFromFormat($format, $time1);
$t2 = DateTime::createFromFormat($format, $time2);
echo "time1" . $t1->format('Y-m-d H:i:s') . "<br/>";
echo "time2" . $t2->format('Y-m-d H:i:s') . "<br/>";
$difference = $t1->diff($t2);
echo $difference->format('%s%a secs');
You can use specific format to create a datetime ojbect, after that you can use diff function to get the difference.
Please try this code.
function time_difference($time_1, $time_2, $limit = null)
{
$val_1 = new DateTime($time_1);
$val_2 = new DateTime($time_2);
$interval = $val_1->diff($val_2);
$output = array(
"year" => $interval->y,
"month" => $interval->m,
"day" => $interval->d,
"hour" => $interval->h,
"minute" => $interval->i,
"second" => $interval->s
);
$return = "";
foreach ($output AS $key => $value) {
if ($value == 1)
$return .= $value . " " . $key . " ";
elseif ($value >= 1)
$return .= $value . " " . $key . "s ";
if ($key == $limit)
return trim($return);
}
return trim($return);
}
$time1 = '2018/04/10 14:54:55';
$time2 = '2018/04/10 14:56:10';
$resp = time_difference ($time1, $time2);
echo $resp;
output:
1 minute 15 seconds
This is an example, I have explained the details in the code itself:
<?php
date_default_timezone_set("Asia/Tehran"); //Set your timezone to avoid warnings in PHP error_log
// Use '/' for American date format and use '-' for Europian date format
// Use 'T' instead of '-'
$time_1 = strtotime( str_replace('-', 'T', "2018/04/10-14:54:55") ); //Replace '-' to 'T' to get "2018/04/10T14:54:55"
$time_2 = strtotime( str_replace('-', 'T', "2018/04/10-14:56:10") ); //Replace '-' to 'T' to get "2018/04/10T14:56:10"
$diff = $time_2 - $time_1;
echo $diff; // in seconds
?>
I hope it helps.

Calculating the difference between dates not working and giving an huge error

Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.
This is how I do the check if the coupon is expired:
if ($date1B > $date2B) {
echo "<script>alert('Expired coupon!!');</script>";
}
Now what I want is to calculate the days when the coupon will be expired.
This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.
$date1 = date("d-m-Y H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
When I replace variables with the existing variables I get these errors:
date_diff() expects parameter 1 to be DateTimeInterface, string given in
and
Call to a member function format() on boolean in
The full .PHP page:
<?php
date_default_timezone_set("America/Curacao");
$date1A = date("d/m/Y H:i:s");
$date1B = date("dmYHis");
$date2B = "27032017042100";
$date2A = date_create_from_format('dmYHis', $date2B);
echo "Datum 1: " . $date1A . "<br>" ;
echo "Datum 1: " . $date1B . "<br><br>";
echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "<br>";
echo "Datum 2: " . $date2B . "<br>";
if ($date1B > $date2B) {
echo "<script>alert('Klaar!!');</script>";
}
$date1 = date("d/m/Y H:i:s");
$date2 = date_format($date2A, 'd/m/Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>
Updated .PHP file
I fixed the errors.. This is the updated .PHP page:
<?php
date_default_timezone_set("America/Curacao");
$date1A = date("d-m-Y H:i:s");
$date1 = date_create($date1A);
echo date_format($date1,"d-m-Y H:i:s");
echo "<br>";
$date2B = "31032017042100";
$date2A = date_create_from_format('dmYHis', $date2B);
$final = date_format($date2A, 'd-m-Y H:i:s');
$date2 = date_create($final);
echo date_format($date2,"d-m-Y H:i:s");
echo "<br>";
$diff = date_diff($date1, $date2);
echo $diff->format("%R %a days %h Hours %i Minute %s Seconds");
if ($date1 > $date2) {
echo "<script>alert('Coupon Expired!!');</script>";
}
?>
The simplest way to calculate the difference between two dates is date_diff() function which gives error on invalid dates.
Before passing on the values to date_diff function you should use the date_create() function.
Usage:
<?php
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
var_export($diff);
Which gives you output like:
DateInterval::__set_state(array( 'y' => 3, 'm' => 1, 'd' => 28, 'h' => 0, 'i' => 0, 's' => 0, 'weekday' => 0, 'weekday_behavior' => 0, 'first_last_day_of' => 0, 'invert' => 0, 'days' => 1154, 'special_type' => 0, 'special_amount' => 0, 'have_weekday_relative' => 0, 'have_special_relative' => 0, ))
UPDATE
You can use or modify the following function to get the difference:
function dateDifference($startDate, $endDate)
{
try {
$startDate = date_create($startDate);
$endDate = date_create($endDate);
$diff = date_diff($startDate, $endDate);
$d = "";
if ($diff->y != 0) {
if ($diff->y > 1) {
$d .= $diff->y . " Years ";
} else {
$d .= $diff->y . " Year ";
}
}
if ($diff->m != 0) {
if ($diff->m > 1) {
$d .= $diff->m . " Months ";
} else {
$d .= $diff->m . " Month ";
}
}
if ($diff->d != 0) {
if ($diff->d > 1) {
$d .= $diff->d . " Days ";
} else {
$d .= $diff->d . " Day ";
}
}
if ($diff->h != 0) {
if ($diff->h > 1) {
$d .= $diff->h . " Hours ";
} else {
$d .= $diff->h . " Hour ";
}
}
if ($diff->i != 0) {
if ($diff->i > 1) {
$d .= $diff->i . " Minutes ";
} else {
$d .= $diff->i . " Minute ";
}
}
if ($diff->s != 0) {
if ($diff->s > 1) {
$d .= $diff->s . " Seconds ";
} else {
$d .= $diff->s . " Second ";
}
}
return $d;
}
catch(Exception $e)
{
die("ERROR");
}
}
Running it like so:
echo dateDifference('2014-10-16', '2017-06-08');
shall output:
2 Years 7 Months 23 Days
Based on #ShaktiPhartiyal answer, to output in the format that you want, just use:
$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
And the output will be:
1154 days 0 Hours 0 Minute 0 Seconds

Convert timestamp to time and keep seconds, minutes and hour

I have a function to convert timestamp to real hour, minute and second, I would to keep the format like: hh:mm:ss even if it is only some minutes and seconds, I should get 00:10:32 instead of 10:32:
// format can be either : or blank
function toTime($timestamp, $format)
{
$hours = floor($timestamp / 3600);
$minutes = floor($timestamp % 3600 / 60);
$seconds = $timestamp % 60;
if($format == ':') {
$hourDuration = sprintf('%02d:', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d:', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = $hourDuration.$minDuration.$secDuration;
} else {
$hourDuration = sprintf('%02d h', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d m', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d s', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = '';
}
if($hourDuration > 0){
$hourDuration = $hourDuration;
} else {
$hourDuration = '';
}
if($minDuration > 0){
$minDuration = $minDuration;
} else {
$minDuration = '';
}
if($secDuration > 0){
$secDuration = $secDuration;
} else {
$secDuration = '';
}
//$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
$HourMinSec = $hourDuration.$minDuration.$secDuration;
return $HourMinSec;
}
This function is used to get a video timestamp like: 1508.7397460938, and I would like to sort out, how many hours, minutes and seconds are in that video
Thanks for your assistance
I would have done it that way
function toTime($timestamp, $format)
{
$hours = floor($timestamp / 3600);
$minutes = floor($timestamp % 3600 / 60);
$seconds = $timestamp % 60;
if($format == ':') {
$hourDuration = sprintf('%02d:', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d:', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = $hourDuration.$minDuration.$secDuration;
} else {
$hourDuration = sprintf('%02d h', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d m', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d s', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = '';
}
if($hourDuration > 0){
$hourDuration = $hourDuration;
} else {
$hourDuration = ($format == ':' ? '00:' : '00 h');
}
if($minDuration > 0){
$minDuration = $minDuration;
} else {
$minDuration = ($format == ':' ? '00:' : '00 m');
}
if($secDuration > 0){
$secDuration = $secDuration;
} else {
$secDuration = '00';
}
//$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
$HourMinSec = $hourDuration.$minDuration.$secDuration;
return $HourMinSec;
}
In that case it would bring you the following result for adding
echo toTime(1508.7397460938);
Output --> 00 h25 m08 s
echo toTime(1508.7397460938,':');
Output --> 00:25:08
The other variant is to use the php ready function gmdate by typing:
echo gmdate("H:i:s", 1508.7397460938);
// Use that only if the amount of hours is less than 24 , that function would now show more than 24 hours and if so it would show inaccurate data.

problems with relative time function in php

I have used many functions for relative time in php but that give different results...help me
My functions :
<?php
function pretty_relative_time($time) {
if ($time !== intval($time)) { $time = strtotime($time); }
$d = time() - $time;
if ($time < strtotime(date('Y-m-d 00:00:00')) - 60*60*24*3) {
$format = 'F j';
if (date('Y') !== date('Y', $time)) {
$format .= ", Y";
}
return date($format, $time);
}
if ($d >= 60*60*24) {
$day = 'Yesterday';
if (date('l', time() - 60*60*24) !== date('l', $time)) { $day = date('l', $time); }
return $day . " at " . date('g:ia', $time);
}
if ($d >= 60*60*2) { return intval($d / (60*60)) . " hours ago"; }
if ($d >= 60*60) { return "about an hour ago"; }
if ($d >= 60*2) { return intval($d / 60) . " minutes ago"; }
if ($d >= 60) { return "about a minute ago"; }
if ($d >= 2) { return intval($d) . " seconds ago"; }
else {return "Just Now"; }
}
function plural($num) {
if ($num != 1)
return "s";
}
function getRelativeTime($date) {
$diff = time() - strtotime($date);
if ($diff<60)
return $diff . " second" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<60)
return $diff . " minute" . plural($diff) . " ago";
$diff = round($diff/60);
if ($diff<24)
return $diff . " hour" . plural($diff) . " ago";
$diff = round($diff/24);
if ($diff<7)
return $diff . " day" . plural($diff) . " ago";
$diff = round($diff/7);
if ($diff<4)
return $diff . " week" . plural($diff) . " ago";
return "on " . date("F j, Y", strtotime($date));
}
echo pretty_relative_time('2012-08-06 8:04:15') ;echo "<br/>";
echo getRelativeTime('2012-08-06 8:04:15');
?>
OutPut :
Just Now // for first function
-15747 seconds ago // for second function
any settings in db ?.....i have used DATETIME for date...
You haven't made clear what output you're expecting, but from your later comment it should be "1 hour ago"? In which case I suspect you are suffering from timezone problems - most likely the dreaded "Daylight Savings Time". Try echoing date('Y-m-d H:i:s') in PHP and seeing if it comes out with the value you expect.
The discrepancy could be in the timezone set in php.ini, or the system clock of the webserver itself, not matching the timezone setting of the database, or the system clock on that server.

Categories