date functionality - date

I want to print 7 days span for a particular date.. I have tried reading php manual and tried several things..nothing is working out.
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd),
date('s',$cd),
date('m',$cd)+$mth,
date('d',$cd)+$day,
date('Y',$cd)+$yr));
return $newdate;
}
?>
but this is not giving me any date.except today's date.

you can use DateTime class:
For example:
$today = new DateTime("now");
$yesterday = $today->modify('-1 day');
$yesterday = get_object_vars($yesterday);
echo $yesterday['date']."<br>";
$twoDaysAgo = $today->modify('-1 day');
$twoDaysAgo = get_object_vars($twoDaysAgo);
echo $twoDaysAgo['date'];

Related

google chart api date format

The below answer suggested works using mysql_ however I have decided to switch to PDO for the increased security if offers. However When I apply the same code, I am struggling to get it to work.I had to switch the while to foreach for PDO.
UPDATE: Using PHP PDO
$sql = "SELECT * FROM userrecords";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row)
{
$dateArray = explode('-', $row['eventdate']);
$year = $dateArray[0];
$month= $dateArray[1] - 1;
$day= $dateArray[2];
$dataArray[] = "[new Date ($year, $month, $day), {$row['scientificname']}, {$row['category_of_taxom']}]";
}
echo $dataArray;
Building on the solution from your other question, you have to parse your dates into javascript's Date object format:
$dataArray = array();
while($row = mysqli_fetch_array($result)) {
$dateArray = explode('-', $row['Date']);
$year = $dateArray[0];
$month = $dateArray[1] - 1; // subtract 1 since javascript months are zero-indexed
$day = $dateArray[2];
$dataArray[] = "[new Date($year, $month, $day), {$row['SpeciesA']}, {$row['Speciesb']}]";
}
Because the json_encode function will break the dates here, we have to parse it into the DataTable constructor a bit differently:
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Species A');
data.addColumn('number', 'Species B');
data.addRows(<?php echo '[' . implode(',', $dataArray) . ']'; ?>);

Strange error in the Zend_Date localization

I have two problems in my little script. I am trying to create an application that use Zend Framework 1.12.1, Doctrine, Zend_locale, Zend_Currency and Zend_Date.
Dates:
The database needs a date in this format Y-m-d H:i:s but each user set their locale preferences in the custom control panel. So when I get a date from the database I have to convert it in the locale choosen.
This is my code:
<?php
$dboutdata = "4/3/13 12:00 AM"; // 4 March 2013 12:00 AM
$date = new Zend_Date($dboutdata, null, "en_US");
echo $date . "<br/>";
$date = new Zend_Date($dboutdata, null, "it_IT");
echo $date . "<br/>";
?>
this is the result:
Apr 3, 13 12:00:00 AM
04/mar/13 12.00.00
As you can see the result is wrong. Zend_Date confuses the month with the day. How have I to solve this problem?
updates:
/**
* Convert a date from yyyy/mm/dd formatted by the locale setting
*
* #param date $dbindata
* #return date formatted by the locale setting
*/
static public function formatDateOut($dbindata) {
if (empty ( $dbindata ))
return false;
$locale = Zend_Registry::get('Zend_Locale');
$date = new Zend_Date($dbindata, "yyyy-MM-dd HH:mm:ss", $locale);
return $date->toString(Zend_Date::DATETIME_SHORT, $locale);
}
/**
* Convert a date from Zend Locale selected to yyyy/mm/dd H:i:s
*
* #param string $dboutdata
* #return string Y-m-d H:i:s
*/
static public function formatDateIn($dboutdata) {
if (empty ( $dboutdata ))
return null;
$InDb = null;
$locale = Zend_Registry::get('Zend_Locale');
$date = new Zend_Date($dboutdata);
return $date->toString('yyyy-MM-dd HH:mm:ss');
}
Furthermore, If I need to save this date how can I normalize it in order to save it in the database?
Best Regards
By passing the locale into the Zend_Date constructor, you're telling it what format the date is in. The US date format has the month first, where as the European date format has the day, so that's why you get different results.
You probably just want to set the locale when outputting the date, e.g.:
$dboutdata = "4/3/13 12:00 AM";
$date = new Zend_Date($dboutdata, null, "en_US");
echo $date->toString(null, 'en_US') . '<br>'; // outputs Apr 3, 13 12:00:00 AM
echo $date->toString(null, 'it_IT') . '<br>'; // outputs 03/apr/13 00.00.00

Which is correct method to compare two dates in PHP?

I've following code to compare two dates in PHP,which one while be appropriate method
<?php
$var = date('d-m-Y',strtotime('29-05-2012'));
$var1 = date('d-m-Y',strtotime('27-06-2012'));
echo $var; //29-05-2012
echo $var1; //27-06-2012
if($var1 >= $var) //method 1
{
echo 'var1 is future date';
}
if(strtotime($var1) >= strtotime($var)) //method 2
{
echo 'var1 is future date(second if)';
}
?>
In above two methods,method-1 is not working,is it not a correct way to compare two dates in PHP ?
No, the first method is incorrect because $var1 and $var are strings, so you can't compare them like that.
However, strtotime() creates unix timestamps (integers), so you can and should compare them like that.
Just leave the date as string, and convert with strtotime in if ().
$a = '29-5-2012';
$b = '27-6-2012';
if (strtotime($a) >= strtotime($b)) {
echo "$a is future date.";
} else {
echo "$b is future date.";
}
// 27-6-2012 is future date.
Depending on you php version >= 5.3 you can try date_diff()
$time1 = strtotime('29-05-2012'); # <--- past
$time2 = strtotime('27-06-2012'); # <--- future
echo max($time1,$time2);
echo "<br />";
echo min($time1,$time2);
why not:
if (mktime(0,0,0,12,31,2012) > mktime(0,0,0,6,25,2011)) {
echo "12/31/2012 is after 6/25/2011";
}
$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));

Zend Google Calendar API - How to Change DateTime Format?

I am using the Zend Framework Gdata for the Google Calendar API and the datetime outputs in RFC3339 (which looks like this: 2012-01-19T22:00:00.000-08:00). What php code do I need to add in order to convert that to UTC so that it looks like this: January 19, 2012 8pm-11pm ? I have found php code that converts RFC dates to string, but I don't know enough about php to be able to alter the code to work with the Zend Gdata formulas... as you will see in my code below, the "date" is referred to as "when"... so any code will have to connect those two somehow... any help is appreciated!
<?php
$path = '/home/ZendGdata/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
// User whose calendars you want to access
$user = 'my#email.com';
$pass = 'mypassword';
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME; // predefined service name for calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$service = new Zend_Gdata_Calendar($client);
$query = $service->newEventQuery();
// Set different query parameters
$query->setUser('mycalendarID');
$query->setVisibility('private');
$query->setProjection('full');
$query->setOrderby('starttime');
// Start date from where to get the events
$query->setStartMin('2012-01-01');
// End date
$query->setStartMax('2050-03-15');
// Get the event list
try {
$eventFeed = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
echo "<ul>";
foreach ($eventFeed as $event) {
echo "<tr>";
foreach ($event->when as $when) {
echo "<td>" . $when->startTime . "</td>";
}
echo "<td>" . $event->content . " </td>";
$where=$event->Where;
foreach($where as $eventplace)
{
echo "<td>" . $eventplace . " </td>";
}
}
echo "</tr>";
echo "</ul>";
?>
Thank you for this information #vascowhite.
Two issues:
The output turned out like this:
string(23) "20 January 2012: 06:00"
I am pulling this info from my google calendar, and it is outputting into my html page...I am not not creating new events through this php...so this code simply converted the date that you wrote, it didn't convert my google calendar event date which is pulled from this code:
foreach ($event->when as $when) {
echo "<td>" . $when->startTime . "</td>";
}
Do you know how to do that?
Thank you,
Susan
You can use PHP's DateTime class to do this quite easily.
First create a DateTime object from your time string:-
$timestr = '2012-01-19T22:00:00.000-08:00';
$date = new DateTime($timestr);
That object is in the correct time zone because of the '-08:00' part of the string.
Now decide which time zone you want to convert to and create a DateTimeZone object (I have chosen UTC as you specifically mention it):-
$tz = new DateTimeZone('UTC');
$date->setTimezone($tz);
Your DateTime object has now been converted to the UTC time zone.
You can get it into your desired format by using the DateTime::format() method:-
var_dump($date->format('d F Y: H:i'));
Output:
20 January 2012: 06:00
To fit into your code:-
foreach ($event->when as $when) {
$date = new DateTime($when->startTime);
echo "<td>" . $date->format('d F Y: H:i') . "</td>";
}

Need help formatting Unix Date from XML output.

I have an events feed from facebook that outputs data in XML format. The dates/ times are in epoch (unix) format, I think. Like so:
<start_time>1319506200</start_time><end_time>1319511600</end_time>
This is dynamic information (events created by a facebook page).
I am using php file_get_contents to place the xml output in my html.
How in the world can I convert the unix dates to a user friendly format? I am at a total loss.
Simply use string date ( string $format [, int $timestamp = time() ] )
Extract the timestamp value from the xml string and pass in as argument #2 to date, as argument #1 you should supply your preferred format string, for example 'Y-m-d T:i:s'
Extracting he timestamp could probably look something like this:
Given that you have the event feed output data stored in a string, in this case $xmlstr
$facebooksomething = new SimpleXMLElement($xmlstr);
date('Y-m-d T:i:s', $facebooksomething->starttime);
Finally got this figured out! :) Woohoo! (changed from the xml feed to json feed by the way) This is what ended up working:
$start_date = date('F j, Y, g:i a', strtotime($json_output2->start_time));
$end_date = date('g:i a', strtotime($json_output2->end_time));
Here is my full code:
<?php
$jsonurl = "https://graph.facebook.com/PAGEID/events?access_token=MYYOKEN";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->data as $data)
{
$jsonurl2 = "https://graph.facebook.com/$data->id/";
$json2 = file_get_contents($jsonurl2,0,null,null);
$json_output2 = json_decode($json2);
$start_date = date('F j, Y, g:i a', strtotime($json_output2->start_time));
$end_date = date('g:i a', strtotime($json_output2->end_time));
echo "{$json_output2->name}\n";
echo "<br>";
echo "{$start_date}\n";
echo " - ";
echo "{$end_date}\n";
echo "<br>";
echo "{$json_output2->description}\n";
echo "<br>Where: ";
echo "{$json_output2->location}\n";
echo "<br><br>";
}
?>