php strtotime function (2) - php

I started to learn PHP and have to find a mistake (maybe in this code):
if($newvalues["year"] != null)
$newvalues["year"] = date("Y-m-d", strtotime($newvalues["year"]."-01-01"));
The new date has to be saved in the array "$newvalues", but when I press the save button, it doesn't save anything. Only if the textfield "year" is empty, the other items can be saved.
Can anyone help me, please?
Thanks.

You're basically doing:
100 * 80 / 80
Just save it as
if($newvalues["year"] != null)
$newvalues["year"] .= "-01-01";
Or better yet, represent it as a DateTime object:
$newvalues = array("year" => 2012);
if ($newvalues["year"] != null) {
$newvalues["year"] = new DateTime("{$newvalues["year"]}-01-01");
}
var_dump($newvalues["year"]);
Using a DateTime object (And the DateTime family) gives you much better and more flexible control over your date/times.

Related

PHP - Handling dates before and after christ

Im making Biogram on my site which lists known historical figures.
Right now, Im just getting values from database, and on many IF statements, determine what to display.
/* #var $bio \Models\Library\Biography */
$birth = [];
$death = [];
$date = null;
if($bio->getBirthMonth() != null) {
if ($bio->getBirthDay() != null) {
$birth = [
$bio->getBirthDay(),
$bio->getBirthMonth(),
$bio->getBirthYear(),
];
} else {
$birth = [
$bio->getBirthMonth(),
$bio->getBirthYear(),
];
}
} else {
$birth = [
$bio->getBirthYear(),
];
}
if($bio->getDeathMonth() != null) {
if ($bio->getDeathDay() != null) {
$death = [
$bio->getDeathDay(),
$bio->getDeathMonth(),
$bio->getDeathYear(),
];
} else {
$death = [
$bio->getDeathMonth(),
$bio->getDeathYear(),
];
}
} else {
$death = [
$bio->getDeathYear(),
];
}
if (!array_filter($birth) && array_filter($death)) {
$date = 'zm. ' . implode('.', $death);
}
if (array_filter($birth) && !array_filter($death)) {
$date = 'ur. ' . implode('.', $birth);
}
if (!array_filter($birth) && !array_filter($death)) {
$date = null;
}
if (array_filter($birth) && array_filter($death)) {
$date = implode('.', $birth) . ' - ' . implode('.', $death);
}
But first of all, Im not happy with this kind of code (don't know if I can write it better).
Secondly when im using Carbon (for example), and want to display year from medival ages, it looks like 0552 instead of 552.
The last thing is that there is no "year 0" in history. There were year 1 After Christ and 1 Before Christ. So when I want to have year -200 it gives me -199.
I know this may be handled by adding -1 to date if it's BC, but I think this is not the right way.
Is there any php library for DateTime that handles all the Dates well?
Also can I, and if so; how to rewrite this code above to look better?
Cheers :)
This is a very interesting problem.
Firstly your if statements - I would write a helper function within $bio that contains the logic regarding what to display as your date, making reference to the other properties that exist within $bio. You could call it getPrettyDate() or something like that. That's potentially where your logic for getting the year to display correctly would go too.
After some considerable googling and not much luck, this answer seems to be the most helpful on this subject, certainly some food for thought.
It's also worth noting that using DATE when persisting this information to your database (assuming you're using MySQL, which you may well not be) is probably not the way forward in your case - as noted in that answer, the MySQL definition of DATE is the following
DATE
A date. The supported range is '1000-01-01' to '9999-12-31'.
I have also after writing this just stumbled across this answer which might be the best approach. Good luck!
More reading on ISO-8601 in the context of 'Year 0' here.

CodeIgniter - MySql timestamp/datetime keep giving me zeros when inserting

I am current using CodeIgniter 2.2.2 and I have the following code inside my modal:
$this->createDate = time();
$this->db->insert('someDB_Table', $this);
Where my createDate type is a timestamp (i also tried datetime). But this is giving me all zeros when inserting inside DB. Is there other way to get around this? Like such: 0000-00-00 00:00:00
Try this(array input method)
$my_array = array(
'database_field' => $this->input->post('input_form_field'),
'time_stamp' => date('Y-m-d H:i:s'),
);
$this->db->insert('someDB_Table', $my_array);
I fixed the error:
this->createDate = date("Y-m-d H:i:s");
Apparently Datetime/Timestamp requires a format to be recognizes in time at insertion. So here you go!
It looks like your are storing the date inside the variable "createDate" which is stored in your structure variable $this. So it is quite the same as $this['createDate'] = time();
Try to do :
$this = time();
$this->db->insert('someDB_Table', $this);
or
$this->createDate = time();
$this->db->insert('someDB_Table', $this->createDate);
I haven't tested it but both of them should work. Also check your table column name (Sometimes bugs comes from that).
Otherwise this is how I do it almost every time:
$date = time();
$mysqli->query("INSERT INTO `someDB_Table`(`createDate`) VALUES (`$date`)");
Good luck ;)

Php-ews: creating contact birthday's event

I am trying to add a contact in Exchange, using the php-ews and the following code:
$request = new EWSType_CreateItemType();
$request->SendMeetingInvitations = 'SendToNone';
$contact = new EWSType_ContactItemType();
$contact->GivenName = $updates['name'];
$contact->Surname = $updates['surname'];
if($updates['email'] != ""){
$email = new EWSType_EmailAddressDictionaryEntryType();
$email->Key = new EWSType_EmailAddressKeyType();
$email->Key->_ = EWSType_EmailAddressKeyType::EMAIL_ADDRESS_1;
$email->_ = $updates['email'];
// set the email
$contact->EmailAddresses = new EWSType_EmailAddressDictionaryType();
$contact->EmailAddresses->Entry[] = $email;
}
$contact->CompanyName = $updates['companyname'];
$contact->JobTitle = $updates['jobtitle'];
$contact->Birthday = $updates['birthday'];
$request->Items->Contact[] = $contact;
$response = $this->ews->CreateItem($request);
Where $updates is an array of strings I have as a parameter.
(I skipped the includes, tell me if you need them.)
Now, the contact gets created and everything works, but the birthday event does not get created automatically in my calendar.
So, I would like to know if there's a simple way to have this done, except the obvious (non-elegant) way of creating it manually.
Thank you in advance,
Riccardo
Could solve this using DateTime in the right format as expected in the comments.
$contact->Birthday = (new DateTime($updates['birthday']))->format(DATE_W3C);
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/time-zones-and-ews-in-exchange
The time zone specified in the value of dateTime elements can take three forms. You can read all the details in XML Schema Part 2: Datatypes Second Edition, but to paraphrase:
Universal Coordinated Time (UTC): Specified by 'Z'. For example, 2014-06-06T19:00:00.000Z
Specific time zone: Specified by '+' or '-' followed by hours and minutes. For example, 2014-06-06T19:00:00.000-08:00
No time zone: Specified by the absence of any time zone. For example, 2014-06-06T19:00:00.000

A way to calculate DateTime intersection where NULL is possible

Background
I'm integrating Limesurvey with an application, where new survey tokens are added directly to the Limesurvey database. Before insertion can be done, I need to check that a given set of tokens (with validfrom and validuntil attributes) in Limesurvey does not intersect with a given range of dates (DateTime).
The problem
Since Limesurveys token validfrom and validuntil attributes can be NULL, a simple comparison of DateTime can't be done, or can it?
(A Limesurvey validfrom/validuntil NULL value implies "always")
What I have
A php class that checks if the Limesurvey attributes are NULL (or not), and returning a calculation of the intersection as needed.
Code: http://phpfiddle.org/main/code/3vp-j3b
(It's what's inside the foreach loop, lines 34-70, that are interesting here)
What I ask
Is there a way to improve/optimise this method, given that the comparison values are special?
You could replace null with a possible first and last date to ease comparing:
if (is_null($token['validfrom']) {
$token_validfrom = new DateTime('0000-01-01 00:00:00');
} else {
$token_validfrom = new DateTime($token['validfrom']);
}
if (is_null($token['validuntil']) {
$token_validuntil = new DateTime('9999-12-31 23:23:59');
} else {
$token_validuntil = new DateTime($token['validuntil']);
}
This way only your last line of comparison should be necessary:
return ($validfrom == $token_validfrom) || ($validfrom > $token_validfrom ? $validfrom < $token_validuntil : $token_validfrom < $validuntil);

Get a "date" type from the DB and add seconds

public function updateAuction($id)
{
$AuctionsTable = Doctrine_Core::getTable('auctions');
$auction = $AuctionsTable->find($id);
$auction->ends_at += 10;
$auction->save();
}
I'm using Doctrine to get a record from the database.
I need to increase number of seconds on this records ends_at column, which is a date type.
+= of course didn't work. What is the quickest way to add, let's say, 10 seconds to ends_at variable? And having handled all the other nuisances that might appear (59 + 10 = 69 seconds).
Perhaps I should use mysql's addtime() function? But is that implemented with Doctrine? Didn't find anything about addtime() on doctrine.
Convert the value from the DB into a DateTime object in PHP
Use the DateTime::add function to add the seconds
Put the resulting value back into the DB
try this:
$sec = new Zend_Date($auction->ends_at, Zend_Date::SECOND);
$auction->ends_at = $sec->addSecond(10);
$auction->save();

Categories