I am currently working on displaying a moment. I want the view to use DateTime->format(..). The value I am getting from the API is 1502462223168. However, this is displayed as 1945-5-26 16:36 instead of 2017-8-11 16:37, since the original value exceeds the PHP_MAX_INT value on the system.
Is there a way I can use the original value, maybe as a String, to create the DateTime object?
since your timestamp value is in milliseconds, divide it by 1000 and then use DateTime, like:
$date = new DateTime();
$stamp = intval(1502462223168/1000);
$date = DateTime::createFromFormat("U", $stamp)->format("Y-m-d H:i:s");
echo $date;
Use this it will be working fine for your question
$timestamp = 1465298940;
$datetimeFormat = 'Y-m-d H:i:s';
$date = new DateTime();
// If you must have use time zones
// $date = new \DateTime('now', new \DateTimeZone('Europe/Helsinki'));
$date->setTimestamp($timestamp);
echo $date->format($datetimeFormat);
Related
Although my question seems can be found the solution on the internet easily. But I've already tried but it's not working.
I've already followed https://www.php.net/manual/en/datetime.diff.php Example #2 DateTime object comparison
or another solution like https://thevaluable.dev/php-datetime-create-compare-format/ Comparing DateTime Objects
But it is still not working.
Here is my code,
$end_time = new DateTime('2020-04-05 23:59:00');
$now = new DateTime('now');
if( $now > $end_time ){
echo 'expired!';
}
It throws the error
Object of class DateTime could not be converted to string.
Edited
I'm using PHP 7.1.23
Here is the solution for your problem. First you have to convert them into Strings then you can use them. I have changed the input date just to show you the result of if condition.
Select your City for time zone First
date_default_timezone_set('Asia/Karachi');
Your Inputs
$input_time = new DateTime('2020-04-01 23:59:00');
$now = new DateTime('now');
Convert them to string
$input_time = $input_time->format('Y-m-d H:i:s');
$now = $now->format('Y-m-d H:i:s');
The result
if( $now > $input_time )
{
echo 'expired!'. '<br>';
}
If it doesn't need to be an actual DateTime object, you could use times instead, which will then compare the same as an integer would.
Eg
$end_time = strtotime('2020-04-05 23:59:00');
$now = time();
if( $now > $end_time ) {
echo 'expired!';
}
What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add expects a DateInterval, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result.
To make a DateInterval from '20:20', I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a DateTime:
$date = new \DateTime('17.03.2016');
$date->add($new \DateInterval('PT20H20M'));
You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.
See DateInterval::__construct to see how to set the intervals.
DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.
Updated
I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.
DateTime
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');
// 2018-10-23 20:20:00
Using DateTime: https://3v4l.org/6eon8
DateTimeImmutable
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');
var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));
Output
string(19) "2018-10-23 00:00:00"
string(19) "2018-10-23 20:20:00"
Using DateTimeImmutable: https://3v4l.org/oRehh
I'm trying to create a DateTime object offset from the present with a specific timezone. It works for 'today', or an absolute value like '2017-07-16 00:00:00', but if I try an offset, like '+1 sundays' it always has a timezone of "S".
$dtz = date_default_timezone_get();//"America/Vancouver"
$now = new \DateTime('today', new \DateTimeZone($dtz));
$sunday = new \DateTime('+1 sundays', new \DateTimeZone($dtz));
$later = new \DateTime('2357-04-13', new \DateTimeZone($dtz));
$tz1 = $now->getTimezone()->getName();//"America/Vancouver"
$tz2 = $sunday->getTimezone()->getName();//"S"
$tz3 = $later->getTimezone()->getName();//"America/Vancouver"
How should I do this?
The first parameter to DateTime should be a valid date/time string. It even takes null when using timezone as second parameter.
'+1 sundays' is not under the category of valid date/time string. Check the complete list here
Below should work -
$sunday = $now->modify('+1 sundays');
echo $sunday->getTimezone()->getName();//"America/Vancouver"
I am trying to compare the current datetime, with a datetime from the database using string, as the following:
$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s');
if($todayString >= $rows["PrioritizationDueDate"])
{...}
$todayString keeps giving me the time 7 hours earlier (i.e now its 11:03pm, its giving me 16:04).
More, is it better to compare this way, or should i compare using datetime objects?
$todayString keeps giving me the time 7 hours earlier
you have to setup a timezone for the DateTime object I believe.
is it better to compare this way
I doubt so.
The general way is to compare in the query, using SQL to do all date calculations and return only matching rows.
Set a correct timezone in the constructor to DateTime.
$today = new DateTime("now", new DateTimeZone('TimezoneString'));
Where TimezoneString is a valid timezone string.
Edit: For a more complete example using DateTime objects, I would use DateTime::diff in conjunction with DateTime::createFromFormat.
$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';
$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));
if( $row_date->diff( $today)->format('%a') > 1)
{
echo 'The row timestamp is more than one day in the past from now.';
}
Demo
First set time zone using this function
date_default_timezone_set('UTC');
Then either you can use function strtotime() or get difference directly...
I am creating a script that allows the user to choose their own timezone...
and enter the date $ time..So the user entered date/time must be converted to GMT format while storing into the database.
While retrieving from the database it should be again converted into original format.
Here DST concept must also be included.
So here date can be in a variable which can be a string or array(multidimensional array also)
So i tried like this.....
function ConvertOneTimezoneToAnotherTimezone($time,$currentTimezone,$timezoneRequired)
{
$current_zone = new DateTimeZone($currentTimezone);
//$gmt = new DateTimeZone('GMT');
$date = new DateTime($time, $current_zone);
//$date->setTimezone($gmt);
$date->setTimezone(new DateTimeZone($timezoneRequired));
return $date->format('Y-m-d H:i:s');
// Convert it back to Original timezone
$date->setTimezone($current_zone);
return $date->format('Y-m-d H:i:s');
}
$time='2011-03-29 11:15:00.000';
echo "Current Date/Time is=".ConvertOneTimezoneToAnotherTimezone($time,'Asia/Kolkata','America/New_York');
but here i am only able to convert into different timezones,but i want a single function which converts date/time and also while retrieving gives original format......
please anybody help me......
<?php
function ConvertOneTimezoneToAnotherTimezone($originalDateTime, $originalTimeZone, $targetTimeZone) {
$format = 'Y-m-d H:i:s';
$dateTime = new DateTime($originalDateTime, new DateTimeZone($originalTimeZone));
$original = $dateTime->format($format);
$dateTime->setTimezone(new DateTimeZone($targetTimeZone));
$target = $dateTime->format($format);
return compact('original', 'target');
}
$dateTime = '2011-03-29 11:15:00.000';
$converted = ConvertOneTimezoneToAnotherTimezone($dateTime,'Asia/Kolkata','America/New_York');
echo sprintf('Original Date/Time is=%s', $converted['original']), PHP_EOL;
echo sprintf('Converted Date/Time is=%s', $converted['target']), PHP_EOL;
something like this
http://service-kl.com/code/tz_demo2/?cou=USA