Datetime diff is not working in php - php

Here $current is the current timestamp and $added_time is the timestamp from when the item is added into the database. Both of them when echoed separately gives the correct o/p but when i try to calculate the difference between them using diff() function, the o/p i get is "Y-m-d H:i:s". What is happening?? I got no clue.
$current = new DateTime();
$diff = $current->diff($added_time);
echo $diff->format('Y-m-d H:i:s');

The diff() method returns a DateInterval object holding the difference of the dates but the usual form Y-m-d H:i:s won't work as is; you need to prefix each format specifier with a percent symbol %
$current = new DateTime();
$diff = $current->diff($added_time);
echo $diff->format('%Y-%m-%d %H:%i:%s');

Related

PHP: why year not subtracted from date?

The below code doesn't subtract 1 year from the date. Why?
$date1 = '2021-06-02';
$date2 = new \DateTime(date($date1, strtotime('-1 year')));
echo $date2->format('Y-m-d'); // outputs the same date 2021-06-02
Part of your problem is that the date function's first argument is the format of the date.
https://www.php.net/manual/en/function.date.php
So what is happening is that you are creating a date string with the format of '2021-06-02'.
https://www.php.net/manual/en/datetime.format.php
This doesn't use anything from the timestamp that you are providing so this string is passed to the constructor of DateTime and creating the date instead of the one from the year previous.
Please use this code. Its always works for me.
$date1 = '2021-06-02';
$date2 = date("Y-m-d", strtotime("-1 year", strtotime($date1)));
echo $date2; //Output 2020-06-02
This is for Date time object:
$dt = new DateTime('2021-06-02');
$minusOneYearDT = $dt->sub(new DateInterval('P1Y'));
$minusOneYear = $minusOneYearDT->format('Y-m-d');
echo $minusOneYear;
OR make a small solution:
$time = new DateTime('2021-06-02');
$newtime = $time->modify('-1 year')->format('Y-m-d');
echo $newtime;
Your code is a bit of a muddle:
date() takes as parameters a format string, and an integer representing a point in time; it then applies the format to create a string for that date and time
strtotime() takes a string, interprets it as a point in time, and returns an integer timestamp
new DateTime() takes a string, in any of the formats strtotime would accept, but creates an object representation rather than returning an integer
You've tried to use all of them at once, and got in a mess:
Your call to date() has a first parameter of '2021-06-02', which isn't a valid format.
Your call to strtotime() has a parameter of '-1 year', which will just be interpreted as "1 year before now", not relative to anything else you've specified.
Using both of those functions and then passing to new \DateTime() doesn't make a lot of sense, since the object can do all the same things those functions can do.
If you want to use the integer-based functions, you could write this:
$date1 = '2021-06-02';
$date2 = strtotime("$date1 -1 year");
echo date('Y-m-d', $date2);
If you want to use the object-based functions, you could write this:
$date1 = '2021-06-02';
$date2 = new \DateTime("$date1 -1 year");
echo $date2->format('Y-m-d');
Or this (note the use of DateTimeImmutable instead of DateTime to avoid the modify method changing the $date1 object:
$date1 = new \DateTimeImmutable('2021-06-02');
$date2 = $date1->modify('-1 year');
echo $date2->format('Y-m-d');

Convert Now and Ten Minutes Ago to Different Timezone

I would like to convert the timestamps from ten minutes ago and now to match the following format:
2018-09-23T04:47:07.237
Here are the timestamps I'd like to convert to match the above format:
$now = date('m/d/y g:i a');
$now = strtotime($now);
$ten_minutes_ago = strtotime('-10 minutes');
How can I do this? Thanks!
Use date_format function instead. You don't need to convert to UNIX timestamp using strtotime function. Instead use DateTime library
Check the following (Rextester Demo):
$now = new DateTime(); // create a datetime object
$sub = new DateInterval("PT10M"); // Interval of 10 mins
$ten_minutes_ago = new DateTime();
$ten_minutes_ago->sub($sub); // subtract 10 minutes
// changed formats
$now_changed = date_format($now, DATE_ISO8601);
$ten_minutes_ago_changed = date_format($ten_minutes_ago, DATE_ISO8601);
// print output
echo $now_changed; //2018-09-23T02:58:25-0400
echo $ten_minutes_ago_changed; // 2018-09-23T02:48:25-0400
Details:
The date_format() function returns a date formatted according to the specified format.
DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
You can check for more formatting options here.
Here is how I would do what you are asking for.
If your data is in a string. Here is the only line of code you need:
$date = date('m/d/y g:i a'); //Gets a date string.
echo substr(date('Y-m-d\TH:i:s.u', strtotime($date . ' -10 minutes')), 0, -3); // PHP < 7.0.0
//echo date('Y-m-d\TH:i:s.v', strtotime($date . ' -10 minutes')); //PHP > 7.0.0
This will produce:
Ex.
09/23/18 12:13 am
To
2018-09-23T00:03:00.000
One thing to note here. The microseconds will always be zeros if your original input date is a string and in the format m/d/y g:i a that you have specified. The reason being is that there is no millisecond information to be had from the date string.
If you create you input date as a dateTime object, the object will be able to keep track of the microseconds for you.

Bad diff between mysql datetime and now datetime object

I want to get time between dates in secounds and here is my code:
$rezultat = $polaczenie->query(sprintf("SELECT terminstart FROM uzytkownicy WHERE id=%d", $_SESSION['id']));
$wiersz = $rezultat->fetch_assoc();
$start = DateTime::createFromFormat('Y-m-d H:i:s', $wiersz['terminstart'])->format('Y-m-d H:i:s');
echo'<script>alert("'.$start.'");</script>';
$teraz = (new \DateTime())->format('Y-m-d H:i:s');
echo'<script>alert("'.$teraz.'");</script>';
$interval = $start->diff($teraz);
echo'<script>alert("'.$interval.'");</script>';
I see from alerts, that $start is working good, $teraz (means now) is working good but I even don't get 3th error with diff. What is the problem?
$start and $teraz are strings, not DateTime objects because you call DateTime::format() on them. You can only do a diff on DateTime objects.
$start = new DateTime($wiersz['terminstart']);
$teraz = new \DateTime();
$interval = $start->diff($teraz);
Also:
Don't use javascript for debugging. That's kinda insane.
You don't need DateTime::createFromFormat() if you date is already in an acceptable format (and Y-m-d H:i:s is an acceptable format)

strtotime with variable using php - object given

This is my current code:
$dateGame = new DateTime();
date_modify($dateGame, "+$universeTime Year");
$arrivalTime = date('Y-M-d H:i:s', strtotime("+$flightTimeMin minutes", $dateGame));
This isn't working because I believe "$dateGame" is an object. How would I turn it into something readable by "strtotime"?
Thanks
You dont need to use strtotime() since you are using datetime and you can use datetime object to format the date as
$universeTime = 3 ;
$flightTimeMin = 20;
$dateGame = new DateTime();
date_modify($dateGame, "+$universeTime Year +$flightTimeMin minutes");
If you want to format the display you can use as
echo $dateGame->format('Y-m-d H:i:s');
or just use
echo $dateGame->date ;

Quicker way to get date of ISO week from a date string?

I'm being passed a date string (most likely in ISO8601 format) and need to convert it to the date of the ISO week to store as a DATETIME column in MySQL. To initialize the DateTime object the I want to save, I'm doing the following:
$date = new DateTime("now");
$date = new DateTime( $date->format("o-\WW") );
echo $date->format(DateTime::ISO8601) . "\n";
Since I'm using Doctrine2, I need to pass my entity a DateTime object. Is there a way to avoid making 2 DateTime objects to get the same result? Should I drop back to the date function and use that as the argument to the DateTime constructor?
$date = new DateTime( date("o-\WW", strtotime("now") );
You could use setISODate to update the first DateTime object using the week and year of the object via format():
$date = new DateTime();
$date->setISODate($date->format('o') , $date->format('W'));
echo $date->format(DateTime::ISO8601);
You could use modify() method of DateTime object.
$date = new DateTime();
$date->modify('sunday this week');
echo $date->format(DateTime::ISO8601) . "\n";
Note that if you want the first day of the week to be something other than Sunday, you will likely need to do something like the following. This example considers Monday as the first day of the week, thus for dates on a Sunday, you would need to get the date of the Monday from the previous week.
$date = new DateTime();
if ($date->format('D') === 'Sun') {
$date->modify('monday last week');
} else {
$date->modify('monday this week');
}
echo $date->format(DateTime::ISO8601) . "\n";
You can probably use date like this:
$date = new DateTime( date('o-\WW') );
Though that formatting looks a bit strange. :p You can of course also use some other method/function the class has to offer to change/modify the date.

Categories