Can't return the current date - php

I've made a function to get the current date with a custom date format, this is the code:
function getTimestamp($dateFormat)
{
$dateFormat = "d-m-Y G:i:s.u";
$originalTime = microtime(true);
$micro = sprintf("%06d", ($originalTime - floor($originalTime)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$micro, $originalTime));
echo $date->format($dateFormat);
return $date->format($dateFormat);
}
the date returned is this:
05-02-2016 0:28:05.839051
but should be this instead:
05-02-2016 0:09:30.839051
what I did wrong?

Use this, it should solve your problem, set locale.
function getTimestamp($dateFormat)
{
$dateFormat = "d-m-Y G:i:s.u";
$originalTime = microtime(true);
$micro = sprintf("%06d", ($originalTime - floor($originalTime)) * 1000000);
$date = new DateTime(date('d-m-Y H:i:s.'.$micro, $originalTime));
$date->setTimezone(new DateTimeZone('Europe/Rome'));
echo $date->format($dateFormat);
return $date->format($dateFormat);
}
did modification to set time zone.
Thanks
Amit

Related

How to set fix time variables in php?

I want to set a fix time variables in php for my if and else condition.
For example:
$startTime = '08:00:00';
$endTime = '16:00:00';
$totalhrs = $endTime - $startTime;
echo $totalhrs;
Anyone know how to declare the time in PHP?
Thanks for the help
$startTime = strtotime('08:00:00');
$endTime = strtotime('16:00:00');
$totalhrs = ($endTime - $startTime) / 3600;
echo $totalhrs;
you can use datetime object for this case
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('16:00:00');
$totalhrs = $startTime->diff($endTime)->h;
You can try the below function to check timestamps. If you don't pass it a second parameter, it will evaluate if the first time has passed the CURRENT time, otherwise it will compare the first time against the second.
Function timeHasPassed($Time, $Time2 = 0) {
If ($Time2 != 0) {
$Now = new DateTime($Time2);
} Else {
$Now = new DateTime();
}
$Then = new DateTime($Time);
If ($Now > $Then) {
Return TRUE;
} Else {
Return FALSE;
/*
You can also use the below code to print out how long is left until the timestamp has passed. Keep in mind, this will return TRUE if tested as a boolean so maybe consider returning a different datatype instead of TRUE if you decide to go this route.
$Time = new DateTime($Time);
$Now = new DateTime();
$Remainder = $Time->diff($Now);
$Remainder = $Remainder->format("%h hours, %i minutes, and %s seconds!");
return $Remainder;
*/
}
}

PHP Datetime: How to get the differnce between DateTime Object and Current Time

I have a DateTime Object and I want to get the differnce between this and the current date. But I always get ZERO as my differnce, but that cannot be. Can't find the answer. Could anyone help me? THANK YOU!
private function checkAge($date) {
$currentDate = date('Y-m-d H:i:s');
$result = $date->format('Y-m-d H:i:s');
$diffDate = ($currentDate-$result);
echo $diffDate;
if ($diffDate>=43200) {
return true;
}
return false;
}
$currentDate and $result are both strings. Subtracting them is not going to give the difference between the two dates.
You can either use the DateTime diff method or, if you just need the seconds you can compare timestamps:
private function checkAge($date) {
$currentDate = date('U');
$result = $date->format('U');
$diffDate = ($currentDate-$result);
echo $diffDate;
if ($diffDate>=43200) {
return true;
}
return false;
}
Have you tried the the diff function to compare dates ?
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

PHP find difference between two linux time

I'm trying to get the difference between two linux times. I want to show the difference in months. I am getting one Linux time from the database and comparing it against time();.
$sql_sms_transactions = "SELECT MAX(`sendtime`) FROM `sms_transaction` where customer_id='$customer_id'";
$result_sms_transactions = mysql_query($sql_sms_transactions);
while($row2=mysql_fetch_assoc($result_sms_transactions))
{
$status = $row2['MAX(`sendtime`)'];
//print $status;
$month = date('m', $status); // 1-12
$year = date('YW', $status);
//print $month;
//print $year;
$current=time();
$monthcurrent = date('m', $current); // 1-12
$yearcurrent = date('YW', $current);
//print $monthcurrent;
//print $yearcurrent;
}
Using DateTime and DateInterval objects, this should work:
$date1 = new DateTime();
$date1->setTimestamp($timestamp1);
$date2 = new DateTime();
$date2->setTimestamp($timestamp2);
$diff = $date1->diff($date2);
// Result of type DateInterval
echo ($diff->y*12) + $diff->m
From what I understand of your code, you have to do this beforehand:
$timestamp1 = time();
$timestamp2 = $status;

Is there any function to find difference between dates and time to date-time in php?

I want the diff between two date-time in php. I want diff in H:i:s format. Here is my code.
$start_date = 2013-08-13;
$end_date = 2013-08-23;
$start_time = 12:28:58;
$end_time = 13:16:45;
$h1 = substr("$start_time",0,-6);
$i1 = substr("$start_time",3,-3);
$s1 = substr("$start_time",6);
$h2 = substr("$end_time",0,-6);
$i2 = substr("$end_time",3,-3);
$s2 = substr("$end_time",6);
$m1 = substr("$start_date",5,-3);
$d1 = substr("$start_date",8);
$y1 = substr("$start_date",0,-6);
$m2 = substr("$end_date",5,-3);
$d2 = substr("$end_date",8);
$y2 = substr("$end_date",0,-6);
$r1=date("Y-m-d H:i:s",mktime($h1,$i1,$s1,$m1,$d1,$y1));
$r2=date("Y-m-d H:i:s",mktime($h2,$i2,$s2,$m2,$d2,$y2));
Why are you performing all those operations when you can use strtotime() ?
It is simpler: if you join dates with times with a space then you can use the aforementioned function to generate a timestamp.
Then, you obtain the difference between the two just with a simple calculation.
Finally, you will format the resulting timestamp with date("H:i:s") (in your case).
Here's the code.
$start_date = "2013-08-13";
$end_date = "2013-08-23";
$start_time = "12:28:58";
$end_time = "13:16:45";
$start_date = $start_date." ".$start_time;
$end_date = $end_date." ".$end_time;
$start_date = strtotime($start_date);
$end_date = strtotime($end_date);
$difference = $end_date - $start_date;
echo date("H:i:s", $difference);
DateTime is the right tool for this job:-
$start_date = '2013-08-13';
$end_date = '2013-08-23';
$start_time = '12:28:58';
$end_time = '13:16:45';
$start = new \DateTime($start_date . ' ' . $start_time);
$end = new \DateTime($end_date . ' ' . $end_time);
$diff = $start->diff($end, true);
$diff is an instance of DateInterval, so you can use DateInterval::format() to echo out the time:-
echo $diff->format("%H:%I:%S");
This is what i used. And its working. If any suggestion please tell. Thanks To all for your reply.
function ensure2Digit($number) {
if($number < 10)
{
$number = '0'.$number;
}
return $number;
}
$start_date = "2013-08-13";
$end_date = "2013-08-23";
$start_time = "12:28:58";
$end_time = "13:16:45";
$start_date = $start_date." ".$start_time;
$end_date = $end_date." ".$end_time;
$start_date = strtotime($start_date);
$end_date = strtotime($end_date);
$difference = $end_date - $start_date;
$h = ensure2Digit(floor($difference / 3600));
$m = ensure2Digit(floor(($difference / 60) % 60));
$s = ensure2Digit($difference % 60);
$time_taken = $h.":".$m.":".$s;
Just whipped up this:
function sec_diff($date_ini, $date_end, $time_ini='00:00:00', $time_end='00:00:00')
{
$d_ini=explode('-', $date_ini);
$h_ini=explode(':', $time_ini);
$d_end=explode('-', $date_end);
$h_end=explode(':', $time_end);
$t_ini=mktime($h_ini[0], $h_ini[1], $h_ini[2], $d_ini[1], $d_ini[2], $d_ini[0]);
$t_end=mktime($h_end[0], $h_end[1], $h_end[2], $d_end[1], $d_end[2], $d_end[0]);
return $t_end-$t_ini;
}
It will get you the difference in seconds. You can easily operate on the result to get the desired format: result / 3600 will give you hours. The rest of that operation will give you spare seconds, that you can / 60 to get minutes. Any rest are seconds.

Timezone conversion in PHP with DateTime

I found some solutions recently and decided to go with this one so I created following method within one of my classes:
public static function date($format, $time = false, $from_timezone = false, $to_timezone = false) {
if (!$time) {
$time = time();
}
if (($from_timezone === $to_timezone) || (!$from_timezone || !$to_timezone)) {
return date($format, $time);
}
$from_tz = new DateTimeZone($from_timezone);
$to_tz = new DateTimeZone($to_timezone);
$dt = new DateTime();
$dt->setTimezone($from_tz);
$dt->setTimestamp($time);
$offset = $to_tz->getOffset($dt);
return date($format, $dt->format('U') + $offset);
}
Then I did a simple test - I converted datetime to some other timezone, and then convert the result back to the original timezone with expectations to get the original datetime.
$format = 'Y-m-d H:i:s';
$initialtime = '2013-06-13 12:00:00';
echo $initialtime;
echo '<br/>';
$convtime = TimezoneLib::date($format, strtotime($initialtime), 'Canada/Atlantic', 'Europe/Prague');
echo $convtime;
echo '<br/>';
echo TimezoneLib::date($format, strtotime($convtime), 'Europe/Prague', 'Canada/Atlantic');
die();
This is the output
2013-06-13 12:00:00 // Original
2013-06-13 14:00:00 // Converted
2013-06-13 11:00:00 // Converted to original timezone
Why dont they match? What am I missing? Thank you.
UPDATE
I am still unable to get matching dates even after removing strtotime. I found out that default timezone also affected DateTime objects. I came up with this:
<?php
class TimezoneLib {
public static $defaultSystemTimezone;
public static function init() {
self::$defaultSystemTimezone = date_default_timezone_get();
}
public static function date($format, $time = false, $from_timezone = false, $to_timezone = false) {
self::switchSystemTimezone($from_timezone);
if (!$time) {
$time = time();
}
if (($from_timezone === $to_timezone) || (!$from_timezone || !$to_timezone)) {
return date($format, $time);
}
$from_tz = new DateTimeZone($from_timezone);
$to_tz = new DateTimeZone($to_timezone);
$dt = new DateTime($time, $from_tz);
self::switchSystemTimezone($to_timezone);
$offset = $to_tz->getOffset($dt);
$convertedDate = date($format, $dt->format('U') + $offset);
self::restoreSystemTimezone();
return $convertedDate;
}
public static function switchSystemTimezone($timezone_identifier) {
return date_default_timezone_set($timezone_identifier);
}
public static function restoreSystemTimezone() {
return date_default_timezone_set(self::$defaultSystemTimezone);
}
}
TimezoneLib::init();
$format = 'Y-m-d H:i:s';
$initialtime = '2013-06-13 12:00:00';
echo $initialtime;
echo '<br/>';
$convtime = TimezoneLib::date($format, $initialtime, 'Canada/Atlantic', 'Europe/Prague');
echo $convtime;
echo '<br/>';
echo TimezoneLib::date($format, $convtime, 'Europe/Prague', 'Canada/Atlantic');
die();
With following output
2013-06-13 12:00:00
2013-06-13 19:00:00
2013-06-13 11:00:00
Create a new DateTime object instead than using strtotime:
$date = new DateTime('your_date_here', DateTimeZone object here);

Categories