I'm using Drupal 7.8, and am trying to get the user to specify a date using the drupal date form. I want to take this date, and save it to a database as a unix timestamp. The trouble is, I think the data given by the date form is based on the user's current timezone. Does drupal provide anyway to convert the form data back to unix time? Is there an easier way to handle dates?
3 Answers
I'm pretty sure the values stored using the date attribute are unaltered and just passed on in an array. So the question would be if the user submits the date for UTC or his/her timezone. I would say the latter ;-)
I'm no expert on date settings and timezones, but had seen this question before on stackoverflow, so taking that into account I assume you can do this:
global $user;
$datefields = $form_state['values']['submitted_date'];
$submittedDate = "{$datefields['year']}-{$datefields['month']}-{$datefields['day']}";
$timezone = $user->timezone;
$newdate = new DateTime($submittedDate, new DateTimeZone($timezone));
$unixts = $newdate->getTimestamp();
This would require the user to have set his/her timezone accurately in the account settings.
-
Thanks for the answer, I'm having a bit of trouble with $user->timezone though, it appears to be a blank string. I have per-user timezones enabled. Any Idea what could be going wrong? Nov 1, 2011 at 0:03
-
Do you have "global $user;" defined? That is needed to access any of the $user properties.– WhiskeyNov 6, 2011 at 15:00
-
I just came across the Date module. This also supports date conversion (in addition to a nice calendar popup I was looking for). From the readme: Example, the following will create a date for the local value in one timezone, adjust it to a different timezone, then return the offset in seconds in the new timezone for the input date; The offset will be adjusted for both the timezone difference and daylight savings time, if necessary: $date = date_create('2007-03-11 02:00:00', timezone_open('America/Chicago')); $chicago_time = date_format($date, 'Y-m-d H:i');– WhiskeyNov 13, 2011 at 22:22
I think you want to store the timestamp of the user, you can use strtotime function for converting the date to unix timestamp. I used the below code for the same :
$date = $date['year'] . '-' . $date['month'] . '-' . $date['day'];
$timestamp = strtotime($date);
Use mktime():
$values = $form_state['values'];
$unix = mktime(0, 0, 0, $values['date']['month'], $values['date']['day'], $values['date']['year']);
This will produce a unix time converted using the time zone of the current user.