1

I am working on a plugin that has a date picker only (no time). I am attempting to set the postDate to the value of whatever date was chosen on the front-end. I realize I need to save in this format: Y-m-d H:i:s

$start = craft()->request->getPost('startDate'); // 09/27/2015

// I'm not doing this right as it returns nothing.
$post = DateTime::createFromString($start); 

// Returns a datetime object, but doesn't save.
$post = new \DateTime($start); 

DateTime Object (
    [date] => 2015-09-27 00:00:00.000000  // trim the last decimal?
    [timezone_type] => 3
    [timezone] => UTC
)

I don't really care what the time is. It could always be midnight, or get the current time from the server. What is the best way to "assemble" the datetime?

5

I believe I have figured it out, please correct me so I can update the answer if I am too far off.

TL;DR:

I am using a date picker (no time) on a front-end form. The user chooses a date and it comes across as 09/27/2015. Here is how I converted that string to a dateTime object that I could set as post & expiry date for a newly created entry.

NOTE: I have not included any validation at this point which should be carefully considered.

MyPlugin.php

// Get the current time zone from the system.
date_default_timezone_set(craft()->timezone);

// Get the current time
$time = date('H:i:s');

// Create the post dateTime
$postDate = date('Y-m-d', strtotime(craft()->request->getPost('postDate')));
$postDateTime = $postDate . ' ' . $time;

// Create the expiry dateTime.
$expireDate = date('Y-m-d', strtotime(craft()->request->getPost('expiryDate')));
$expireDateTime = $expireDate . ' ' . $time;

// Create the DateTime object to send to Craft.
$postDate = new \DateTime($postDateTime);
$expiryDate = new \DateTime($expireDateTime);

// Put it all together.
$entry = new EntryModel();

$entry->sectionId = 3;
$entry->typeId = 1;
$entry->enabled = true;
$entry->postDate = $postDate;
$entry->expiryDate = $expiryDate;

...

if(craft()->entries->saveEntry($entry)) {
    // Success
} else {
    // Fail
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.