Php time and datatime object - php

So,
I know a lot of requests and question has been askeb about this subject but none really worked for my case... I'm working on a liscensing api with php (supposed to be easy) and I get a string date (2000-01-01) from my db and the length of the subscription. So I'm creating a DateTime Object with it using this :
$created_at = date_create($result["created_at"]);
date_add($created_at, date_interval_create_from_date_string($result["length"]." days"));
But for some unknowed reason, It seems I can't get the current date in a DateTime object so I can just compare them with <>=. Even if I use date_sub() or date_diff() It still require two DateTime object. I'm really deseperate at this point so I figured I could ask for some help.
Hope I didn't miss anything obvious

You can use the 'now' attribute,
$today = new DateTime('now'); to get the current time.
Don't forget to set your timeregion in your php.ini to be able to get the right time.
And if you want to compare them, you can use date_diff and then
$var->format('%r') to get the value.
%r is going to be empty if the result is positive.
Good luck!

Related

Set date range for lineItem using GoogleAds API

I have been having trouble trying to figure out how to set a range of dates for a given lineItem using the google ads php client library. Basically, what I want to do is make a line item to be available for a specified start date and an end date but no success. In their example they have this snippet:
$lineItem->setStartDateTimeType(StartDateTimeType::IMMEDIATELY);
$lineItem->setEndDateTime(
AdManagerDateTimes::fromDateTime(
new DateTime('+1 month', new DateTimeZone('America/New_York'))
)
);
They're setting a start date for the line item to IMMEDIATELY, and and end date to 1 month from the time of creation. I tried passing to AdManagerDateTimes::fromDateTimeString a valid ISO 8601 string and no luck (GAM spits an error). Tried creating a DateTime() instance and passing it to the code above, nothing. I'm not too experienced in php and maybe this is way easier than i think it is but I'm stuck.
Any tips please?
Thank you
i don't know if you already solve this issue, but you can change in the new DateTime include the date you want
$lineItem->setEndDateTime(
AdManagerDateTimes::fromDateTime(
new DateTime('2023-02-12')
)
);

Convert timestamp coming from SQL database to String

I am saving the timestamp in SQL as bigint(20). The number is correct and in android or https://www.epochconverter.com it works fine.
However I am not able to create a date-string based on the timestamp received from database.
First of all, the timestamp seems to come from database as a String, so I can't just say echo date("d.m.Y, $timestamp). The result is the famous 31.12.1969.
So I tried echo date("d.m.Y, strtotime($timestamp)). However, even though strtotime is said to be able to convert almost everything to a timestamp, a simple String containing a timestamp is not possible. Results still remained on the last day of Brian Adams probably favorite year.
Some progress I made by casting the $timestamp to a float value like so: echo date("d.m.Y", floatval($timestamp));. However, now things got really confusing for me. I seemed to have successfully converted my timestamp, however, date() gave me the dates around 02.09.52299.
The timestamps I am using are timestamps of current time, e.g. 1588489252657, which currently leads to the date 23.03.52307.
So all I want is to come to a date based on the timestamp 1588489252657 to see the 03.05.2020 on my screen.
Thanks for any advice!
<?php
$timestamp = 1588489252657; // Timestamp in Milliseconds
$seconds = round($timestamp/1000, 0); // Timestamp Rounded to Seconds
$date = new DateTime(); // Create PHP DateTime Object
$date->setTimestamp($seconds); // Set the Timestamp
echo $date->format('Y-m-d H:i:s'); // Specify the Required Format
The answers are pretty much in the comment sections. But I have shared this answer since this is another approach in OOP fashion. You can leverage the power of PHP's DateTime Class.
PHP Official Documentation For DateTime Class Link Below:
PHP DateTime Class
You have to transform the timestamp to seconds first.
$timestamp = 1588489252657;
$dateInUnixSeconds = round($timestamp / 1000, 0);
$date = \DateTimeImmutable::createFromFormat('U', (string) $dateInUnixSeconds);
echo $date->format('d.m.Y');
PS:
I recommend you to use the \DateTimeImmutable object to avoid mutability problems.
https://github.com/Chemaclass/php-best-practices/blob/master/technical-skills/immutability.md

Change DateTime() offset in PHP

Is it possible in PHP to change the DateTime() to a custom time difference. Like adding it 20 min and everytime I call new DateTime() I would get those extra 20 min to the current date.
I thought about __construct() but didn't see how to fix it.
I can use a function of course, but just curious to know if its possible to change the prototype new DateTime()
Yes, it's possible:
$date = new DateTime();
$date->modify("+20 minutes"); //or whatever value you want
Example online
Ilia Rostovtsev's answer is a good one for achieving your goal. Alternatively you can also use the DateInterval class with DateTime::add(). Personally, I prefer that one because you don't need to know how strings need to look like while DateInterval uses a standard like P1d for a day.
I wouldn't use inheritance to get a DateTime class including your wished behaviour. Instead you can create some kind of factory which contains Ilia's code (and every other code that is part for the object creation). The interval can be added as parameter. Your added interval, your 20 minutes should be stored in a constant in case you need to change that interval in the future while technically being able to use other intervals than 20 minutes.
You can do this all in one line:-
$date = (new \DateTime())->add(new \DateInterval('PT20M'));
That would be my preferred way of doing it.
See it working in PHP >= 5.3

Reformatting datetime

Ok, so I've got a time string like this:
2013-08-09T15:00:00
Now as far as I can tell, I'll need to convert this to a timestamp, before I can change the formatting - is that correct, or is there a shorter step? For example using one of the classes here:
http://philsturgeon.co.uk/blog/2012/08/why-php-datetime-rocks
I'm not quite sure what the "T" represents (besides time, obviously) and I'm not sure what format that is.
I want to get it into standard 12 hour time.
Use DateTime()
$dt = new DateTime('2013-08-09T15:00:00');
echo $dt->format('Y-m-d h:i:s');

How to create DateTime object from string in symfony2/php

In a DB table I have several fields with datetime as field type. So I need to persist data only as date time object.
From a form I get date time as string like
2012-10-05 17:45:54
Now when ever I persist my entity I get following error:
Fatal error: Call to a member function format() on a non-object in
..\DateTimeType.php on line 44
I tried with
$protocol->setStartedAt(strtotime($post['started_at']));
or
$from = \DateTime::createFromFormat('yy-mm-dd hh:mm:ss', $post['started_at']);
$protocol->setStartedAt($from);
or just
$from = new \DateTime($post['started_at']);
$protocol->setStartedAt($from);
The last code works but it does not uses the timestamp passed as arguement but just gets the current time.
Any ideas?
I always create a DateTime object with its constructor, in your case it would be:
$protocol->setStartedAt(new \DateTime($post['started_at']));
if this works but does not use the timestamp posted you probably do not have the value in $post['started_at']. Try debugging it or just do the dirty trick:
die($post['started_at']);
For the sake of future readers who surely will someday encounter this problem (this is the first post if you google "symfony 2 datetime from string"), keep in mind that in Symfony 2 the DateTime object does NOT accept a string with that format : "d/m/Y H:i:s", and probably doesn't support many others either.
For the sake of not becoming mad at that, I've actually found out that the easiest and safest solution to avoid such errors is this one:
First, get your date string from whatever kind of request you are doing (In my case a generic AJAX request) and convert it to a DateTime Object, this example assumes that we need to create a dateTime object for 25/04/2015 15:00, which is the format of the jQuery UI italian DateTimePicker (that's just an example):
$literalTime = \DateTime::createFromFormat("d/m/Y H:i","25/04/2015 15:00");
(note: use \ to use php's DateTime object, else you will be using Symfony's datetime object that will throw you an exception)
Then, once you did it, create a date string using the comfort format function, by giving to the first parameter the output format expected (Y-m-d H:i:s):
$expire_date = $literalTime->format("Y-m-d H:i:s");
In this way you are 100% sure that whatever kind of format you are passing or receiving this will properly be converted and you won't get any kind of exception from the DateTime symfony object, as long as you provide what you are expecting as an input.
Knowing that this post is actually quite old, I've just decided to post that because I didn't find any other valuable source but this one to understand where the problem could have been.
Please note that the best solution is still to send the datetime string in the correct format already, but if you literally have no ways to do that the safest way to convert such a string is the one above.
How about createFromFormat?
http://uk.php.net/manual/en/datetime.createfromformat.php
$from = DateTime::createFromFormat($post['started_at'], 'Y-m-d H:i:s');

Categories