Skip to content

Instantly share code, notes, and snippets.

@pfaocle
Created September 27, 2012 19:22
Show Gist options
  • Save pfaocle/3795910 to your computer and use it in GitHub Desktop.
Save pfaocle/3795910 to your computer and use it in GitHub Desktop.
PHP for CMS Developers - DateTime exercise
<html>
<head>
<title>PHP for CMS Developers - Exercise 1</title>
</head>
<body>
<p>Enter a date, using a format understood by <a href="http://php.net/manual/en/class.datetime.php">http://php.net/manual/en/class.datetime.php</a></p>
<form method="post">
Date: <input type="text" name="date" maxlength="20" />
<br />
<input type="submit" value="Submit" />
</form>
<?php
if ($_POST) {
$output_format = 'jS F, Y'; // like 1st January, 2012
$utc_output_format = 'jS F, Y e'; // UTC
$weeks_to_add = 3;
$interval_format = "P{$weeks_to_add}W";
$sDateString = filter_input(INPUT_POST, 'date', FILTER_SANITIZE_STRING);
if (!empty($sDateString)) {
echo 'String submitted: ' . $sDateString . "<br />\n";
try {
$sDate = new DateTime($sDateString);
$sDate->setTimezone(new DateTimeZone('Europe/London'));
}
catch (Exception $e) {
echo 'Error: that was not a valid date format. Details: ' . $e;
exit;
}
// No __toString() for this object...
echo 'Date object created: ' . $sDate->format($output_format) . "<br />\n";
// Add 3 weeks and display in UTC format
$sDate->add(new DateInterval($interval_format));
$sDate->setTimezone(new DateTimeZone('UTC'));
echo 'Date object altered: ' . $sDate->format($utc_output_format) . "<br />\n";
}
else {
echo 'Nothing entered. Try again...';
}
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment