converting m/d/yy to mm/dd/yyyy in php - php

Im pulling column from excel with dates, and with the code i have to verify if row has date in it works fine for when dates in mm/dd/yyyy (07/05/2015) format. it passes date verify function and I'm able to grab that date and store it in mysql date formate column. but problem comes in when I'm reading excel file that has date format m/d/yy (7/5/15) I'm not sure at what point its failing but when i look at it database the dates are converted to weird dates and its skipping most of the dates from failing at date verify function. what i would like to do is convert the string I'm fetching from excel from m/d/yy to mm/dd/yyyy before it gets to date verify function. can anyone tell me how can i achieve that?
this is my function to verify if its date.
public function is_date( $str ) /// function to check if its date
{
$stamp = strtotime( $str );
if (!is_numeric($stamp))
return FALSE;
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year))
return TRUE;
return FALSE;
}
this is the part where it gets the date and sends to database
foreach(array_slice($sheetData, $dateRow-1) as $item)
{
$value = trim($item["{$revCol}"], "$");
$value = str_replace(",", "", $value);
$value = str_replace("?", "", $value);
//check if its date or garbage data
if ($this->is_date( $item["{$dateCol}"]) /* && $this->isCurrency($temp) */)
{
$key = $item["{$dateCol}"];
$key = date('Y-m-d', strtotime($key));
$sold = $item["{$soldCol}"];
$params = array('key' => $key);
$oldVal->execute($params);
$results = $oldVal->fetch(); // fetch old value before replacing with new
$old_rev = $results['rev'];
$old_sold = $results['sold'];
$diff_rev = $value - $old_rev;
$diff_rev = number_format($diff_rev, 2, '.', '');
$diff_sold = $sold - $old_sold;
//$insertDiff->execute(array($key, $diff_rev, $diff_sold));
$newVal->execute(array($key, $value, $diff_rev, $sold, $diff_sold));
}
}

Try this code to convert it ...
$date = "7/5/15";
$your_date = date("m/d/Y", strtotime($date));
echo $your_date;
It will echo 07/05/2015
Here you have the example online

You can format the column in Excel as a date with leading zeroes. That seems the quickest solution.

is this what you want? strtotime undestands such format
$str = '7/5/15';
echo date("m/d/Y", strtotime($str)); // 07/05/2015

strtotime should do the work.
Try replacing '/' by '-'
$stamp = strtotime( str_replace('/', '-' ,$str ) );
If not, the problem happen all time with the format m/d/yy or just in some cases (for example for days greater than 12 or something like that ?

Related

how to get Random date between 2 date values using php? [duplicate]

I am coding an application where i need to assign random date between two fixed timestamps
how i can achieve this using php i've searched first but only found the answer for Java not php
for example :
$string = randomdate(1262055681,1262055681);
PHP has the rand() function:
$int= rand(1262055681,1262055681);
It also has mt_rand(), which is generally purported to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
A quick PHP example would be:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.
Another solution using PHP DateTime
$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.
function randomDateInRange(DateTime $start, DateTime $end) {
$randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
$randomDate = new DateTime();
$randomDate->setTimestamp($randomTimestamp);
return $randomDate;
}
You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.
For example, to get a date a random numbers days between now and 30 days out.
echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
Here's another example:
$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
echo "\$randomday: $randomday\n";
echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";
The best way :
$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );
By using carbon and php rand between two dates
$startDate = Carbon::now();
$endDate = Carbon::now()->subDays(7);
$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');
OR
$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');
An other solution where we can use date_format :
/**
* Method to generate random date between two dates
* #param $sStartDate
* #param $sEndDate
* #param string $sFormat
* #return bool|string
*/
function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
// Convert the supplied date to timestamp
$fMin = strtotime($sStartDate);
$fMax = strtotime($sEndDate);
// Generate a random number from the start and end dates
$fVal = mt_rand($fMin, $fMax);
// Convert back to the specified date format
return date($sFormat, $fVal);
}
Source : https://gist.github.com/samcrosoft/6550473
You could use for example :
$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');
The amount of strtotime in here is WAY too high.
For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:
function random_date_in_range( $date1, $date2 ){
if (!is_a($date1, 'DateTime')) {
$date1 = new DateTime( (ctype_digit((string)$date1) ? '#' : '') . $date1);
$date2 = new DateTime( (ctype_digit((string)$date2) ? '#' : '') . $date2);
}
$random_u = random_int($date1->format('U'), $date2->format('U'));
$random_date = new DateTime();
$random_date->setTimestamp($random_u);
return $random_date->format('Y-m-d') .'<br>';
}
Call it any number of ways ...
// timestamps
echo random_date_in_range(157766400,1489686923);
// any date string
echo random_date_in_range('1492-01-01','2050-01-01');
// English textual parsing
echo random_date_in_range('last Sunday','now');
// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);
As is, the function requires date1 <= date2.
i had a same situation before and none of the above answers fix my problem so i
Came with new function
function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
//inspired by
// https://gist.github.com/samcrosoft/6550473
// Convert the supplied date to timestamp
$minDateString = strtotime($startDate);
$maxDateString = strtotime($endDate);
if ($minDateString > $maxDateString)
{
throw new Exception("From Date must be lesser than to date", 1);
}
for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++)
{
$randomDate[] = mt_rand($minDateString, $maxDateString);
}
if (sizeof($randomDate) == 1)
{
$randomDate = date($dateFormat, $randomDate[0]);
return $randomDate;
}elseif (sizeof($randomDate) > 1)
{
foreach ($randomDate as $randomDateKey => $randomDateValue)
{
$randomDatearray[] = date($dateFormat, $randomDateValue);
}
//return $randomDatearray;
return array_values(array_unique($randomDatearray));
}
}
Now the testing Part(Data may change while testing )
$fromDate = '2012-04-02';
$toDate = '2018-07-02';
print_r(randomDate($fromDate,$toDate,1));
result will be
2016-01-25 11:43:22
print_r(randomDate($fromDate,$toDate,1));
array:10 [▼
0 => "2015-08-24 18:38:26"
1 => "2018-01-13 21:12:59"
2 => "2018-06-22 00:18:40"
3 => "2016-09-14 02:38:04"
4 => "2016-03-29 17:51:30"
5 => "2018-03-30 07:28:48"
6 => "2018-06-13 17:57:47"
7 => "2017-09-24 16:00:40"
8 => "2016-12-29 17:32:33"
9 => "2013-09-05 02:56:14"
]
But after the few tests i was thinking about what if the inputs be like
$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';
So the duplicates may occur while generating the large number of dates such as 10,000
so i have added array_unique and this will return only the non duplicates
if you use laravel then it's for you.
\Carbon\Carbon::now()->subDays(rand(0, 90))->format('Y-m-d');
Simplest of all, this small function works for me
I wrote it in a helper class datetime as a static method
/**
* Return date between two dates
*
* #param String $startDate
* #param String $endDate
* #return String
*
* #author Kuldeep Dangi <kuldeepamy#gmail.com>
*/
public static function getRandomDateTime($startDate, $endDate)
{
$randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
return date(self::DATETIME_FORMAT_MYSQL, $randomTime);
}
Pretty good question; needed to generate some random sample data for an app.
You could use the following function with optional arguments to generate random dates:
function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
return $result;
}
sample input:
echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00
echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>';
//1942/Jan/19 00:00 AM
echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January
echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00
echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00
echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00
readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.
Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .
The function accepts:
start date
end date
format: any php accepted format for date or time
timezone: name or offset number
mode: debug, epoch, verbose epoch or verbose
the output in not debug mode is random number according to optional specifications.
tested with PHP 7.x
// Find a randomDate between $startDate and $endDate
function randomDate($startDate, $endDate)
{
// Convert to timetamps
$min = strtotime($startDate);
$max = strtotime($endDate);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to date
return Carbon::createFromTimestamp($val);
}
dd($this->randomDate('2014-12-10', Carbon::now()->toString()));
Using carbon
$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);
Full random date and time

How to make PHP see a datetime value for what it is

I'm passing the following value via URL to PHP:
&newtimestamp=2016-12-21%2014:44:44.
Instead of %20 I've tried with +.
In PHP I have this:
$newtimestamp = $_GET["newtimestamp"];
Which correctly shows the timestamp if I do:
echo ($newtimestamp);
But when trying:
echo date_format($newtimestamp,'U');
or
echo date_format($newtimestamp,'Y-m-d H:i:s');
I get no output at all. And later in the script, the input is used to compare against an SQL table:
$sql = ("SELECT sender,subject,timestamp,threadid,username,notify,msgtype FROM Messages WHERE sender = '$usernametmp' AND subject !='' AND timestamp > '$newtimestamp' ORDER BY timestamp");
And I get no results at all.
I do get results If I manually set the timestamp to
$newtimestamp = '1985-10-07 11:42:12';
I was thinking that I need to define it as datetime with:
$timestamp = new DateTime($newtimestamp);
But then I get a server error.
PHP version is 5.3, by the way. and needs to be changed by my hosting provider. If that's the solution, is there a lot of stuff running with 5.3 that will no longer work with 5.5 or 5.6 (this is what they offer)?
I hope someone can see what I'm doing wrong here, thanks in advance!
You need to use the date_create function and decode the URL on the GET like this:
<?php
$newtimestamp=date_create(urldecode($_GET['newtimestamp']));
echo date_format($newtimestamp,"Y/m/d H:i:s");
You cannot compare human time to unix time format, unix time looks like this
1483319956
So you probably need a function to help you do that
try this custom function i wrote
change_date_to_timestamp($date_string)
{
$array = explode(' ', $date_string);
$date = $array[0];
$date = explode('-', $date);
$year = (int)$date[0];
$month = (int)$date[1];
$day = (int)$date[2];
$hour = 00;
$minute = 00;
$second = 00;
if (isset($array[1])) {
$time = $array[1];
$time = explode(':', $time);
$hour = (int)$time[0];
$minute = (int)$time[1];
$second = (int)$time[2];
}
$stamp = mktime($hour, $minute, $second, $month, $day, $year);
return $stamp;
}
Refactor as pleased

Verifiying 2 date to make sure they're valid dates

I am working with a date which is formatted like so:
25/02/1994 - 15/03/2000
To get each date I am using the explode function to separate each date between dash
$newdate = explode("-",$olddate);
Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)
What would be the best way to validate the date for legitimacy?
You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.
In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.
<?php
$str = "25/02/1994 - 15/03/2000";
$dates = explode("-", $str);
if(array_reduce($dates, function($keep, $date){
list($day, $month, $year) = array_map("trim",explode("/", $date));
if(!checkdate($month, $day, $year))
return $keep = FALSE;
return $keep;
}, TRUE)) {
echo "all valid dates";
}
?>
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$first_date = explode("/", trim($date_array[0]));
$second_date = explode("/", trim($date_array[1]));
if(checkdate($first_date[1],$first_date[0],$first_date[2])){
//do stuff
}
if(checkdate($second_date[1],$second_date[0],$second_date[2])){
//do stuff
}
or, what Daan suggested using the DateTime object.
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$date1 = DateTime::createFromFormat('j-M-Y', $date_array[0]);
$date2 = DateTime::createFromFormat('j-M-Y', $date_array[1]);
if($date1){
//do stuff
}
if($date2){
//do stuff
}

Convert user input to my date format

User enters the date as 8/1/11 or 08/1/11. Regardless of how the user inputs the date in my text field, I want to convert what they enter to my format of mm/dd/yyyy
So if the user enters 8/1/11 it would convert it to 08/01/2011.
Use strtotime() to transfer it into a time value, and then mktime() to transfer it to whatever format you want.
EDIT: Turns out it's not that simple.
You can't just print any date you'd like and transfer it to another, it'll be best to use some sort of UI on the client side to ensure the input matches, a great example is jQueryUI Datepicker
Check this.
It also checks if the date is valid (with checkdate) and converts years from short to long. When using short years, 0-69 is converted to 2000-2069 and 70-99 is converted to 1970-1999.
<?php
function cleanDate($input)
{
$parts = explode('/', $input);
if(count($parts) != 3) return false;
$month = (int)$parts[0];
$day = (int)$parts[1];
$year = (int)$parts[2];
if($year < 100)
{
if($year < 70)
{
$year += 2000;
}
else
{
$year += 1900;
}
}
if(!checkdate($month, $day, $year)) return false;
return sprintf('%02d/%02d/%d', $month, $day, $year);
// OR
$time = mktime(0, 0, 0, $month, $day, $year);
return date('m/d/Y', $time);
}
$test = array(
'08/01/2011', '8/1/11', '08/01/11', // Should all return 08/01/2011
'08/1/87', // Should return 08/01/1987
'32/1/93', '13', // Should fail: invalid dates
'02/29/2011', // Should fail: 2011 is not a leap year
'2/29/08'); // Should return 02/29/2008 (2008 is a leap year)
foreach($test as $t)
{
echo $t.' : '.(cleanDate($t) ?: 'false')."\n";
}
?>
Result:
08/01/2011 : 08/01/2011
8/1/11 : 08/01/2011
08/01/11 : 08/01/2011
08/1/87 : 08/01/1987
32/1/93 : false
13 : false
02/29/2011 : false
2/29/08 : 02/29/2008
<?php
$userInput = '08/1/11'; // or = '8/1/11' or = '08/01/11' or = '01/8/11'
$arr = explode('/', $userInput);
$formatted = sprintf("%1$02d", $arr[0]) . '/' . sprintf("%1$02d", $arr[1]) . '/20' . $arr[2];
?>
<?php
preg_match('#^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\d{2})$#',trim($date),$matches);
$month=str_pad($matches[1],2,'0',STR_PAD_LEFT);
$day=str_pad($matches[2],2,'0',STR_PAD_LEFT);
$year=$matches[3];
$result="{$month}/{$day}/{$year}";
?>
While #Truth is right that the user can do a lot to make it difficult, there IS actually a way to do a fairly decent job of parsing a date input box to work. It takes into account a variety of user input issues that may come up.
Note that it does make two assumptions:
That the local uses a date format of m/d/y
If the year is entered in short form, we are dealing with a 2000+ year
<?php
// Trim spaces from beginning/end
$date = trim(request($field));
// Allow for the user to have separated by spaces
$date = str_replace(" ", "/", $date);
// Allow for the user to have separated by dashes or periods
$date = str_replace("-", "/", str_replace(".", "/", trim($date)));
// Explode the date parts out to ensure a year
// Granted, this is geo-centric - you could adjust based on your locale
$dateparts = explode("/", $date);
// Check for a year. If not entered, assume this year
if (!isset($dateparts[2])) {$dateparts[2] = date("Y");}
// Force year to integer for comparison
$dateparts[2] = (int)$dateparts[2];
// Allow for user to use short year. Assumes all dates will be in the year 2000+
if ($dateparts[2] < 2000) {$dateparts[2]+= 2000;}
// Re-assemble the date to a string
$date = implode("/", $dateparts);
// Utilize strtotime and date to convert date to standard format
$date = date("m/d/Y", strtotime($date));
?>
Disclaimer: Yes, this is the verbose way of doing this, however I did so for clarity of the example, not for efficiency.

php check for a valid date, weird date conversions

Is there a way to check to see if a date/time is valid you would think these would be easy to check:
$date = '0000-00-00';
$time = '00:00:00';
$dateTime = $date . ' ' . $time;
if(strtotime($dateTime)) {
// why is this valid?
}
what really gets me is this:
echo date('Y-m-d', strtotime($date));
results in: "1999-11-30",
huh? i went from 0000-00-00 to 1999-11-30 ???
I know i could do comparison to see if the date is either of those values is equal to the date i have but it isn't a very robust way to check. Is there a good way to check to see if i have a valid date? Anyone have a good function to check this?
Edit:
People are asking what i'm running:
Running PHP 5.2.5 (cli) (built: Jul 23 2008 11:32:27) on Linux localhost 2.6.18-53.1.14.el5 #1 SMP Wed Mar 5 11:36:49 EST 2008 i686 i686 i386 GNU/Linux
From php.net
<?php
function isValidDateTime($dateTime)
{
if (preg_match("/^(\d{4})-(\d{2})-(\d{2}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)) {
if (checkdate($matches[2], $matches[3], $matches[1])) {
return true;
}
}
return false;
}
?>
As mentioned here: https://bugs.php.net/bug.php?id=45647
There is no bug here, 00-00-00 means 2000-00-00, which is 1999-12-00,
which is 1999-11-30. No bug, perfectly normal.
And as shown with a few tests, rolling backwards is expected behavior, if a little unsettling:
>> date('Y-m-d', strtotime('2012-03-00'))
string: '2012-02-29'
>> date('Y-m-d', strtotime('2012-02-00'))
string: '2012-01-31'
>> date('Y-m-d', strtotime('2012-01-00'))
string: '2011-12-31'
>> date('Y-m-d', strtotime('2012-00-00'))
string: '2011-11-30'
echo date('Y-m-d', strtotime($date));
results in: "1999-11-30"
The result of strtotime is 943920000 - this is the number of seconds, roughly, between the Unix epoch (base from which time is measured) to 1999-11-30.
There is a documented mysql bug on mktime(), localtime(), strtotime() all returning this odd value when you try a pre-epoch time (including "0000-00-00 00:00:00"). There's some debate on the linked thread as to whether this is actually a bug:
Since the time stamp is started from 1970, I don't think it supposed to
work in anyways.
Below is a function that I use for converting dateTimes such as the above to a timestamp for comparisons, etc, which may be of some use to you, for dates beyond "0000-00-00 00:00:00"
/**
* Converts strings of the format "YYYY-MM-DD HH:MM:SS" into php dates
*/
function convert_date_string($date_string)
{
list($date, $time) = explode(" ", $date_string);
list($hours, $minutes, $seconds) = explode(":", $time);
list($year, $month, $day) = explode("-", $date);
return mktime($hours, $minutes, $seconds, $month, $day, $year);
}
Don't expect coherent results when you're out of range:
cf strtotime
cf Gnu Calendar-date-items.html
"For numeric months, the ISO 8601
format ‘year-month-day’ is allowed,
where year is any positive number,
month is a number between 01
and 12, and day is a
number between 01 and 31. A
leading zero must be present if a
number is less than ten."
So '0000-00-00' gives weird results, that's logical!
"Additionally, not all
platforms support negative timestamps,
therefore your date range may be
limited to no earlier than the Unix
epoch. This means that e.g.
%e, %T, %R and %D (there might be
more) and dates prior to Jan
1, 1970 will not work on Windows, some
Linux distributions, and a few other
operating systems."
cf strftime
Use checkdate function instead (more robust):
month:
The month is between 1 and 12 inclusive.
day:
The day is within the allowed number of days for the given
month. Leap year s are taken
into consideration.
year:
The year is between 1 and 32767 inclusive.
This version allows for the field to be empty, has dates in mm/dd/yy or mm/dd/yyyy format, allow for single digit hours, adds optional am/pm, and corrects some subtle flaws in the time match.
Still allows some pathological times like '23:14 AM'.
function isValidDateTime($dateTime) {
if (trim($dateTime) == '') {
return true;
}
if (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})(\s+(([01]?[0-9])|(2[0-3]))(:[0-5][0-9]){0,2}(\s+(am|pm))?)?$/i', $dateTime, $matches)) {
list($all,$mm,$dd,$year) = $matches;
if ($year <= 99) {
$year += 2000;
}
return checkdate($mm, $dd, $year);
}
return false;
}
If you just want to handle a date conversion without the time for a mysql date field, you can modify this great code as I did.
On my version of PHP without performing this function I get "0000-00-00" every time. Annoying.
function ConvertDateString ($DateString)
{
list($year, $month, $day) = explode("-", $DateString);
return date ("Y-m-d, mktime (0, 0, 0, $month, $day, $year));
}
<?php
function is_valid_date($user_date=false, $valid_date = "1900-01-01") {
$user_date = date("Y-m-d H:i:s",strtotime($user_date));
return strtotime($user_date) >= strtotime($valid_date) ? true : false;
}
echo is_valid_date("00-00-00") ? 1 : 0; // return 0
echo is_valid_date("3/5/2011") ? 1 : 0; // return 1
I have been just changing the martin answer above, which will validate any type of date and return in the format you like.
Just change the format by editing below line of script
strftime("10-10-2012", strtotime($dt));
<?php
echo is_date("13/04/10");
function is_date( $str ) {
$flag = strpos($str, '/');
if(intval($flag)<=0){
$stamp = strtotime( $str );
} else {
list($d, $m, $y) = explode('/', $str);
$stamp = strtotime("$d-$m-$y");
}
//var_dump($stamp) ;
if (!is_numeric($stamp)) {
//echo "ho" ;
return "not a date" ;
}
$month = date( 'n', $stamp ); // use n to get date in correct format
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year)) {
$dt = "$year-$month-$day" ;
return strftime("%d-%b-%Y", strtotime($dt));
//return TRUE;
} else {
return "not a date" ;
}
}
?>
I have used the following code to validate dates coming from ExtJS applications.
function check_sql_date_format($date) {
$date = substr($date, 0, 10);
list($year, $month, $day) = explode('-', $date);
if (!is_numeric($year) || !is_numeric($month) || !is_numeric($day)) {
return false;
}
return checkdate($month, $day, $year);
}
<?php
function is_date( $str ) {
$stamp = strtotime( $str );
if (!is_numeric($stamp)) {
return FALSE;
}
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (checkdate($month, $day, $year)) {
return TRUE;
}
return FALSE;
}
?>

Categories