Function to check if a string is a date - php

I am trying to write a function to determine if a string is a date/time using PHP. Basically a valid date/time would look like:
2012-06-14 01:46:28
Obviously though its completely dynamic any of the values can change, but it should always be in form of XXXX-XX-XX XX:XX:XX, how can I write a regular expression to check for this pattern and return true if matched.

If that's your whole string, then just try parsing it:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== false) {
// it's a date
}

Easiest way to check if a string is a date:
if(strtotime($date_string)){
// it's in date format
}

Here's a different approach without using a regex:
function check_your_datetime($x) {
return (date('Y-m-d H:i:s', strtotime($x)) == $x);
}

In case you don't know the date format:
/**
* Check if the value is a valid date
*
* #param mixed $value
*
* #return boolean
*/
function isDate($value)
{
if (!$value) {
return false;
}
try {
new \DateTime($value);
return true;
} catch (\Exception $e) {
return false;
}
}
var_dump(isDate('2017-01-06')); // true
var_dump(isDate('2017-13-06')); // false
var_dump(isDate('2017-02-06T04:20:33')); // true
var_dump(isDate('2017/02/06')); // true
var_dump(isDate('3.6. 2017')); // true
var_dump(isDate(null)); // false
var_dump(isDate(true)); // false
var_dump(isDate(false)); // false
var_dump(isDate('')); // false
var_dump(isDate(45)); // false

In my project this seems to work:
function isDate($value) {
if (!$value) {
return false;
} else {
$date = date_parse($value);
if($date['error_count'] == 0 && $date['warning_count'] == 0){
return checkdate($date['month'], $date['day'], $date['year']);
} else {
return false;
}
}
}

I use this function as a parameter to the PHP filter_var function.
It checks for dates in yyyy-mm-dd hh:mm:ss format
It rejects dates that match the pattern but still invalid (e.g. Apr 31)
function filter_mydate($s) {
if (preg_match('#^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$#', $s, $m) == false) {
return false;
}
if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
return false;
}
return $s;
}

Although this has an accepted answer, it is not going to effectively work in all cases. For example, I test date validation on a form field I have using the date "10/38/2013", and I got a valid DateObject returned, but the date was what PHP call "overflowed", so that "10/38/2013" becomes "11/07/2013". Makes sense, but should we just accept the reformed date, or force users to input the correct date? For those of us who are form validation nazis, We can use this dirty fix: https://stackoverflow.com/a/10120725/486863 and just return false when the object throws this warning.
The other workaround would be to match the string date to the formatted one, and compare the two for equal value. This seems just as messy. Oh well. Such is the nature of PHP dev.

A simple solution is:
echo is_numeric( strtotime( $string ) ) ? 'Yes' : 'No';

if (strtotime($date) > strtotime(0)) {
echo 'it is a date'
}

I found my answer here https://stackoverflow.com/a/19271434/1363220, bassically
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
if($d && $d->format($format) === $date) {
//it's a proper date!
}
else {
//it's not a proper date
}

I wouldn't use a Regex for this, but rather just split the string and check that the date is valid:
list($year, $month, $day, $hour, $minute, $second) = preg_split('%( |-|:)%', $mydatestring);
if(!checkdate($month, $day, $year)) {
/* print error */
}
/* check $hour, $minute and $second etc */

If your heart is set on using regEx then txt2re.com is always a good resource:
<?php
$txt='2012-06-14 01:46:28';
$re1='((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))'; # Time Stamp 1
if ($c=preg_match_all ("/".$re1."/is", $txt, $matches))
{
$timestamp1=$matches[1][0];
print "($timestamp1) \n";
}
?>

If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:
class ExDateTime extends DateTime{
public static function createFromFormat($frmt,$time,$timezone=null){
$v = explode('.', phpversion());
if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
return parent::createFromFormat($frmt,$time,$timezone);
}
return new DateTime(date($frmt, strtotime($time)), $timezone);
}
}
and than you can use this class without problems:
ExDateTime::createFromFormat('d.m.Y G:i',$timevar);

function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net

This solves for me, but also presents various other problems I think.
function validateTimeString($datetime, $format = "Y-m-d H:i:s"){
return ($datetime == date($format, strtotime($datetime)));
}

When I work with unconventional APIs, I sometimes get a bit of a messy return instead of a well defined date format. So I use a rather inelegant class and I readily admit that it is brutal and unconventional in principle but it does me good sometimes ^^.
class DateHelper
{
private const DATE_FORMATS = [
DATE_ATOM,
DATE_COOKIE,
DATE_RFC822,
DATE_RFC850,
DATE_RSS,
DATE_W3C,
"Y-m-d\TH:i:s.u",
'Y-m-d\TH:i:s',
"Y-m-d'T'H:i:s.SSS'Z'",
"Y-m-d\TH:i:s.uP",
"Y-m-d\TH:i:sP",
"d/m/Y H:i:s",
];
/**
* #param string $inputStringDate
* #return DateTime|null
*/
public static function createDateFromUnknownFormat(string $inputStringDate): ?DateTime
{
$inputStringDate = str_replace('/', '-', $inputStringDate);
preg_match('/^(\d{4})\-(\d{2})-(\d{2})$/', $inputStringDate, $result);
if (!empty($result)) {
return DateTime::createFromFormat('Y-m-d', $inputStringDate);
}
preg_match('/^(\d{2})\-(\d{2})-(\d{4})$/', $inputStringDate, $result);
if (!empty($result)) {
return DateTime::createFromFormat('d-m-Y', $inputStringDate);
}
foreach (self::DATE_FORMATS as $dateFormat) {
if ($dateObject = DateTime::createFromFormat($dateFormat, $inputStringDate)) {
return $dateObject;
}
}
return null;
}
}

strtotime? Lists? Regular expressions?
What's wrong with PHP's native DateTime object?
http://www.php.net/manual/en/datetime.construct.php

Related

Date Validation Codeigniter

I'm creating a validation for the post in my Controller.
I have a problem about the date.
I have created in applications/libraries a MY_Form_validation.php page in which I wrote this:
public function valid_date($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($date, $format);
return $d && $d->format($format) === $date;
}
Then I have created the form_validation_lang.php with
<?php
$lang['form_validation_valid_date'] = 'The field {field} is not a valid date';
While in my controller I have:
//load the libraries
$this->form_validation->set_rules('birthdate', 'birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$errors = $this->form_validation->error_array();
var_dump($errors);
$this->response($errors, 500);
return;
}
$person = array(
//..
'birthdate' => $this->post('birthdate'),
//...
);
It prints me that:
'birthdate' => 'string'
About my DB at the beginning my field was Data, and i received this error. Than I have changed to Datetime but the error is the same.
Now it's:
birthdate date NOT NULL,
Now for example I'm trying to post a date like '1960-04-20' and I receive back the error:
"birthdate": "The field birthdate is not a valid date"
I want to write in the db only the date and not the time, could be this the problem??
How can I do to validate date?
Thank you
Replace your function with next:
public function valid_date($date, $format = 'Y-m-d') {
$d = new DateTime($date);
return $d && $d->format($format) === $date;
}
Demo
Or with next one:
public function valid_date($date, $format = 'Y-m-d') {
$d = DateTime::createFromFormat($format,$date); // <-- replace arguments
return $d && $d->format($format) === $date;
}
Demo
DateTime::createFromFormat() documentation
You need to cast this string, after success validation, into DATE datatype and only then send it into DB. Or you can write "to_date($stringvar,$format)" in your SQL query.
Seems like CodeIgniter doesn't likes default variables in validation options. I mean, you can't declare $format = 'Y-m-d' as an argument. So, it would work if you won't use it:
public function valid_date_dmY($str)
{
$d = DateTime::createFromFormat('d.m.Y',$str);
return $d && $d->format('d.m.Y') === $str;
}

How to summarize multiple Intervals in PHP

In my app I can create projects and for each project I can record work reports. Each report has a start and an end timestamp. A table in the project description shows every report for this project and it also calculates the duration (with DateTime and the diff() function used between start and end timestamp). Now I want to calculate the total work time on the projects but I have no idea how I can do this. I already tried looping through all reports somehow and then use DateTime functions, but I'm getting nowhere... My last desperate attempt was this:
public static function calculateDuration($start, $end)
{
$start = date('Y-m-d H:i:s', $start);
$end = date('Y-m-d H:i:s', $end);
$s = new \DateTime($start);
$e = new \DateTime($end);
$interval = $e->diff($s);
return $interval->format('%H:%I');
}
public static function calculateTotal($idProject)
{
$reports = self::find('id_project = "' . $idProject . '"');
$totalReports = new \DateTime();
foreach ($reports as $report) {
$totalReports->add(new \DateInterval(self::calculateDuration($report->getStart(), $report->getEnd())));
}
/*echo '<pre>';
die(var_dump($totalReports));
echo '</pre>';*/
return $totalReports->format('H:I');
}
the calculateDuration functions works perfectly, but of course calculateTotal doesn't, because DateInterval does not take a string like "0:30". So that is completely useless...
I hope I provided all the needed information, just let me know if you need something else.
For clarity on my comments: You already have calculateDuration doing all the work, and it internally deals with a DateInterval object. So why not make use of it? Here, getInterval is a protected method that's used by both existing methods and returns the DateInterval object directly. Now calculateDuration becomes a simple formatting function, and calculateTotal has access to the DateInterval object.
protected static function getInterval($start, $end)
{
$s = new \DateTime('#' . $start);
$e = new \DateTime('#' . $end);
return $e->diff($s);
}
public static function calculateDuration($start, $end)
{
return self::getInterval($start, $end)->format('%H:%I');
}
public static function calculateTotal($idProject)
{
// ...
$totalReports = new \DateTime();
$totalReportsEnd = clone $totalReports;
foreach ($reports as $report) {
$totalReportsEnd->add(self::getInterval(
$report->getStart(),
$report->getEnd()
));
}
$totalInterval = $totalReportsEnd->diff($totalReports);
// do as you wish with the interval
}
Just create a valid DateInterval format instead of returning hours and minutes:
// Untested. Might need escaping.
return $interval->format('PT%HH%IM');

PHP Optional Function Arguments

I'm a little stuck trying to create a function that takes a single, optional argument. Instead of this being a string I'd like it to be the result of a function (or even better, a DateTime object). Essentially - I want the user to either pass in a DateTime object, or for the function to resort to todays date if no arguments are supplied. Is this possible with PHP? By trying to create the new object in the function header as such
function myDateFunction($date = new DateTime()){
//My function goes here.
}
causes PHP to fall over.
Many thanks.
Yes. It is possible if you move $date instantiation to function body:
<?php
header('Content-Type: text/plain');
function myDateFunction(DateTime $date = null){
if($date === null){
$date = new DateTime();
}
return $date->format('d.m.Y H:i:s');
}
echo
myDateFunction(),
PHP_EOL,
myDateFunction(DateTime::createFromFormat('d.m.Y', '11.11.2011'));
?>
Result:
15.09.2013 17:25:02
11.11.2011 17:25:02
From php.net:
Type hinting allowing NULL value
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
http://php.net/manual/en/functions.arguments.php#example-154
You can do it this way:
function myDateFunction($date = null){
if(is_null($date) || !($date instanceof DateTime)) {
$date = new DateTime();
}
return $date;
}
var_dump(myDateFunction());
You can use other option:
function myDateFunction($date = null){
if(is_null($date)) $date = new DateTime();
}
function myDateFunc($date = null){
if(!isset($date) || $date !instanceof DateTime){
$date = new DateTime()
}
/* YOur code here*/
}
for optional argument in your function, you can write code like
function myDateFunction($date = ''){
//My function goes here.
if($date==''){ $date = new DateTime()}
}
hope it helps

PHP validate ISO 8601 date string

How do you validate ISO 8601 date string (ex: 2011-10-02T23:25:42Z).
I know that there are several possible representations of ISO 8601 dates, but I'm only interested in validating the format I gave as an example above.
Thanks!
I want to share my lightweight solution. It is not ideal, but might be helpful for someone.
function validISO8601Date($value)
{
if (!is_string($value)) {
return false;
}
$dateTime = \DateTime::createFromFormat(\DateTime::ISO8601, $value);
if ($dateTime) {
return $dateTime->format(\DateTime::ISO8601) === $value;
}
return false;
}
Atention!
Some valid ISO8601 dates will fail Look at the list below
NOT VALID --> '' // Correct
NOT VALID --> 'string' // Correct
VALID --> '2000-01-01T01:00:00+1200' // This is the only format function returns as valid
NOT VALID --> '2015-01 first' // Correct
NOT VALID --> '2000-01-01T01:00:00Z' // Must be valid!
NOT VALID --> '2000-01-01T01:00:00+01' // Must be valid!
This worked for me, it uses a regular expression to make sure the date is in the format you want, and then tries to parse the date and recreate it to make sure the output matches the input:
<?php
$date = '2011-10-02T23:25:42Z';
var_dump(validateDate($date));
$date = '2011-17-17T23:25:42Z';
var_dump(validateDate($date));
function validateDate($date)
{
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $date, $parts) == true) {
$time = gmmktime($parts[4], $parts[5], $parts[6], $parts[2], $parts[3], $parts[1]);
$input_time = strtotime($date);
if ($input_time === false) return false;
return $input_time == $time;
} else {
return false;
}
}
You could expand further to use checkdate to make sure the month day and year are valid as well.
Edit: By far the easiest method is to simply try to create a DateTime object using the string, eg
$dt = new DateTime($dateTimeString);
If the DateTime constructor cannot parse the string, it will throw an exception, eg
DateTime::__construct(): Failed to parse time string (2011-10-02T23:25:72Z) at position 18 (2): Unexpected character
Note that if you leave off the time zone designator, it will use the configured default timezone.
Second easiest method is to use a regular expression. Something like this aught to cover it
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(\+|-)\d{2}(:?\d{2})?)$/', $dateString, $parts)) {
// valid string format, can now check parts
$year = $parts[1];
$month = $parts[2];
$day = $parts[3];
// etc
}
See http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/. It gives this regex to use:
^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$
I suppose this does not answer your question exactly, since it will match any valid ISO 8601 date, but if that is alright then this works perfectly.
This is the function I use. It is similar to the answer of drew010 but works also for timestamps ending with "+01:00" or "-01:00".
function isTimestampIsoValid($timestamp)
{
if (preg_match('/^'.
'(\d{4})-(\d{2})-(\d{2})T'. // YYYY-MM-DDT ex: 2014-01-01T
'(\d{2}):(\d{2}):(\d{2})'. // HH-MM-SS ex: 17:00:00
'(Z|((-|\+)\d{2}:\d{2}))'. // Z or +01:00 or -01:00
'$/', $timestamp, $parts) == true)
{
try {
new \DateTime($timestamp);
return true;
}
catch ( \Exception $e)
{
return false;
}
} else {
return false;
}
}
Carbon is handling this part really well
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
...
/** #test */
public function checking_iso8601_date()
{
$this->expectException(InvalidFormatException::class);
Carbon::createFromFormat('c', '2021-05-11 20:03:45+02:00');
$this->assertInstanceOf(Carbon::class, Carbon::createFromFormat('c', '2021-05-11T20:03:45+02:00'));
}
You may do the same with DateTime
use DateTime;
...
/** #test */
public function checking_iso8601_date()
{
$this->assertInstanceOf(DateTime::class, DateTime::createFromFormat('Y-m-d\TH:i:sP', '2021-05-11T20:03:45+02:00'));
$this->assertFalse(DateTime::createFromFormat('Y-m-d\TH:i:sP', '2021-05-11 20:03:45+02:00'));
}

Refactoring JavaScript and PHP code [Job Interview]

recently I had a job interview. I had two tasks:
1) to refactor a JavaScript code
// The library 'jsUtil' has a public function that compares 2 arrays, returning true if
// they're the same. Refactor it so it's more robust, performs better and is easier to maintain.
/**
#name jsUtil.arraysSame
#description Compares 2 arrays, returns true if both are comprised of the same items, in the same order
#param {Object[]} a Array to compare with
#param {Object[]} b Array to compare to
#returns {boolean} true if both contain the same items, otherwise false
#example
if ( jsUtil.arraysSame( [1, 2, 3], [1, 2, 3] ) ) {
alert('Arrays are the same!');
}
*/
// assume jsUtil is an object
jsUtil.arraysSame = function(a, b) {
var r = 1;
for (i in a) if ( a[i] != b[i] ) r = 0;
else continue;
return r;
}
2) To refactor a PHP function that checks for a leap year
<?php
/*
The class 'DateUtil' defines a method that takes a date in the format DD/MM/YYYY, extracts the year
and works out if it is a leap year. The code is poorly written. Refactor it so that it is more robust
and easier to maintain in the future.
Hint: a year is a leap year if it is evenly divisible by 4, unless it is also evenly
divisible by 100 and not by 400.
*/
class DateUtil {
function notLeapYear ($var) {
$var = substr($var, 6, 4);
if (! ($var % 100) && $var % 400) {
return 1;
}
return $var % 4;
}
}
$testDates = array('03/12/2000', '01/04/2001', '28/01/2004', '29/11/2200');
/* the expected result is
* 03/12/2000 falls in a leap year
* 01/04/2001 does not fall in a leap year
* 28/01/2004 falls in a leap year
* 29/11/2200 does not fall in a leap year
*/
?>
<? $dateUtil = new DateUtil(); ?>
<ul>
<? foreach ($testDates as $date) { ?>
<li><?= $date ?> <?= ($dateUtil->notLeapYear($date) ? 'does not fall' : 'falls') ?> in a leap year</li>
<? } ?>
</ul>
I think I cope with the task but I am not quite sure, I still don't have an answer from them and it's been about a week. Could you give an example of your approach to this tasks? I'd really appreciate. Later I can post my solutions/code.
OK here are my answers to the questions.
<?php // Always use full/long openning tags not
$start = microtime(true);
class DateUtil {
/**
* The date could be used in other
* class methods in the future.
* Use just internally.
**/
var $_date;
/**
* The constructor of the class takes
* 1 argument, date, as a string and sets
* the object parameter _date to be used
* internally. This is compatable only in PHP5
* for PHP4 should be replaced with function DateUtil(...)
*/
public function __construct( $date = '' ) {
$this->_date = $date;
}
/**
* Setter for the date. Currently not used.
* Also we could use _set magical function.
* for PHP5.
**/
public function setDate( $date = '' ) {
$this->_date = $date;
}
/**
* Gettre of the date. Currently not used.
* Also we could use _get magical function.
* for PHP5.
**/
public function getDate() {
return $this->_date;
}
public function isLeapYear( $year = '' ) {
// all leap years can be divided through 4
if (($year % 4) != 0) {
return false;
}
// all leap years can be divided through 400
if ($year % 400 == 0) {
return true;
} else if ($year % 100 == 0) {
return false;
}
return true;
}
}
$dates = array('03/12/2000', '01/04/2001', '30/01/2004', '29/11/2200');
$dateUtil = new DateUtil();
foreach($dates as $date) {
/**
* This processing is not done in the class
* because the date format could be different in
* other cases so we cannot assume this will allways
* be the format of the date
*
* The php function strtotime() was not used due to
* a bug called 2K38, more specifically dates after and 2038
* are not parsed correctly due to the format of the UNIX
* timestamp which is 32bit integer.
* If the years we use are higher than 1970 and lower
* than 2038 we can use date('L', strtotime($date));
**/
$year = explode('/', $date);
$year = $year[2];
$isLeap = $dateUtil->isLeapYear($year);
echo '<pre>' . $date . ' - ';
echo ($isLeap)? 'Is leap year': 'Is not leap year';
echo '</pre>';
}
echo 'The execution took: ' . (microtime(true) - $start) . ' sec';
?>
JavaScript
/***************************************************/
jsUtil = new Object();
jsUtil.arraysSame = function(a, b) {
if( typeof(a) != 'object') {
// Check if tepes of 'a' is object
return false;
} else if(typeof(a) != typeof(b)) {
// Check if tepes of 'a' and 'b' are same
return false;
} else if(a.length != b.length) {
// Check if arrays have different length if yes return false
return false;
}
for(var i in a) {
// We compare each element not only by value
// but also by type so 3 != '3'
if(a[i] !== b[i]) {
return false;
}
}
return true;
}
// It will work with associative arrays too
var a = {a:1, b:2, c:3};
var b = {a:1, b:2, c:3}; // true
var c = {a:1, b:2, g:3}; // false
var d = {a:1, b:2, c:'3'}; // false
var output = '';
output += 'Arrays a==b is: ' + jsUtil.arraysSame( a, b );
output += '\n';
output += 'Arrays a==c is: ' + jsUtil.arraysSame( a, c );
output += '\n';
output += 'Arrays a==d is: ' + jsUtil.arraysSame( a, d );
alert(output);
Iterate arrays using a for loop rather than for...in. If the arrays are different, you want to return as quickly as possible, so start with a length comparison and return immediately you come across an element that differs between the two arrays. Compare them using the strict inequality operator !==. Iterate backwards through the array for speed and to minimise the number of variables required by assigning a's length to i and reusing i as the iteration variable.
This code assumes that the parameters a and b are both supplied and are both Array objects. This seems to be implied by the question.
var jsUtil = jsUtil || {};
jsUtil.arraysSame = function(a, b) {
var i = a.length;
if (i != b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
};
For the PHP version:
class DateUtil {
function LeapYear ($var) {
$date = DateTime::CreateFromFormat($var, 'd/m/Y');
return($date->format('L')); // returns 1 for leapyear, 0 otherwise
}
function notLeapYear($var) {
return(!$this->LeapYear($var)) {
}
}
For the first problem maybe I can help you with this:
var jsUtil = jsUtil || {};
jsUtil.arraysSame = function(a, b){
//both must be arrays
if (!a instanceof Array || !b instanceof Array) {
return false;
}
//both must have the same size
if (a.length !== b.length) {
return false;
}
var isEquals = true;
for (var i = 0, j = a.length; i < j; i++) {
if (a[i] !== b[i]) {
isEquals = false;
i = j; //don't use break
}
}
return isEquals;
}
I included type checking and made the things more clear.
In my opinion using built-in predefined functions is always your best bet.
1) Use a function that converts the arrays into strings. There are many of these available and depending on which library you are already using you may want to use different ones. You can find one at Json.org
jsUtil.arraysSame = function(a, b) {
return JSON.stringify(a) == JSON.stringify(b);
}
2) USe PHP's built in date function and strtotime
class DateUtil {
function notLeapYear ($var) {
return (date( 'L', strtotime( $var)) == "0");
}
}
check inputs (type, range - keep in mind that very old dates used a different calendar); you might use PHP date functions to parse date (more flexibility on one hand, limited to relatively recent dates on the other)
never iterate with in in javascript, will fail horribly when prototypes of the standard types have been extended
you should clarify what the functions should do; e.g. should the array comparison be recursive? Should it use strict equivalence?
you can stop iterating the arrays when the first difference is found. Also, you might want to check if the two refer to the same object before starting to iterate.
write unit tests

Categories