Find out whether string has date in it - php

I have a string "scbdemo2016-10-21:getlastweekReadBooks4795".
How to find out the above string has date in it and to validate the date is current day date.

Easily done with regular expressions:
$isToday = stringDateToday("scbdemo2016-10-21:getlastweekReadBooks4795");
function stringDateToday($string) {
$reg = "/\d{4}-\d{2}-\d{2}/";
$date = new DateTime();
preg_match($reg, $string, $matches);
if (isset($matches[0])) {
return $matches[0] == $date->format("Y-m-d");
}
return false;
}
stringDateToday() will return true if the date in the string is today. The date can be anywhere in the string.
EDIT:
As suggested in the comments, you may want to change new DateTime() to new DateTime('now', new DateTimeZone('Europe/London')) to specify timezone.

Here is your code, but it only works with string that has : character, anyways
function checkdata($date, $format)
{
$format=strstr(preg_replace("/[a-zA-Z]+/", '',$format),":",true);
// date_default_timezone_set('UTC');
$d = DateTime::createFromFormat($format, $date);
if($d && $d->format($format) === $date) {
return true;
} else {
return false;
}
}
$data="scbdemo2016-10-21:getlastweekReadBooks4795";
if(checkdata($data,'Y-m-d'))
echo "Yes";
else
echo "NO";

Related

Retrieve date format and parse if needed in PHP

I've created this function when retrieving a date from database and echo in Italian format to screen:
function get_data_ita($date) {
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
where $date is mysql format like: 2017-12-31 14:00:00
Now, if I pass a correct format like: 2017-12-31 14:00:00 the function works.
But sometimes I need to use the SAME function, passing an already formatted date like: 30/12/2017. In this case, i get parsing error of course.
How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
I need a function like:
function get_data_ita($date) {
if ( $date== ALREADY_IN_ITALIAN_FORMAT )
return $date;
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
ECHO:
30/12/2017
31/12/2017
UPDATE: I found solution myself:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function get_data_ita($datetime_db) {
if ( validateDate($datetime_db, 'd/m/Y') ) {
return $datetime_db;
}
if ($datetime_db == "")
return "";
$date = new DateTime($datetime_db);
return $date->format('d/m/Y');
}
Replace / to -
<?php
function get_data_ita($date) {
if ($date == ""){
return "";
}
$date = str_replace('/','-',$date);
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo "\n";
echo get_data_ita("2017-12-31 14:00:00");
?>
Check demo : https://eval.in/918149
Strtotime returns false if the date is not a valid date format.
This works for your inputs but not if there are other date formats.
function get_data_ita($date) {
if ($date == "") return "";
If(strtotime($date) !== False){
$d = new DateTime($date);
}Else{
$d = DateTime::createFromFormat('d/m/Y', $date);
}
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
https://3v4l.org/kt5Vg

Check if 2 given dates are a weekend using PHP

I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.
I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
A couple of hints:
date('N') gives you normalised week day you can test against (no need to use localised strings)
Wrap it all in a custom function and you're done
You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6.
So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:
$date1 = '2011-01-01' ;
$date2 = '2017-05-26';
if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend($date) {
return (date('N', strtotime($date)) >= 6);
}
Using your existing code, which is slightly longer, following is how you would check for 2 dates:
$date1 = '2011-01-01' ;
$date2 = '2017-05-27';
if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend_long($date_str) {
$timestamp = strtotime($date_str);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
//echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
return true;
} else {
return false;
}
}
Merging multiple answers into one and giving a bit extra, you'd come to the following:
function isWeekend($date) {
return (new DateTime($date))->format("N") > 5 ? true : false;
}
Or the long way:
function isWeekend($date) {
if ((new DateTime($date))->format("N") > 5) {
return true;
}
return false;
}
You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun
function check_if_weekend($date){
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if(in_array($day, array('sun', 'sat'))
return true;
else return false;
}

php date validation

Im trying to to set up a php date validation (MM/DD/YYYY) but I'm having issues. Here is a sample of what I got:
$date_regex = '%\A(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d\z%';
$test_date = '03/22/2010';
if (preg_match($date_regex, $test_date,$_POST['birthday']) ==true) {
$errors[] = 'user name most have no spaces';`
You could use checkdate. For example, something like this:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
}
A more paranoid approach, that doesn't blindly believe the input:
$test_date = '03/22/2010';
$test_arr = explode('/', $test_date);
if (count($test_arr) == 3) {
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2])) {
// valid date ...
} else {
// problem with dates ...
}
} else {
// problem with input ...
}
You can use some methods of the DateTime class, which might be handy; namely, DateTime::createFromFormat() in conjunction with DateTime::getLastErrors().
$test_date = '03/22/2010';
$date = DateTime::createFromFormat('m/d/Y', $test_date);
$date_errors = DateTime::getLastErrors();
if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
$errors[] = 'Some useful error message goes here.';
}
This even allows us to see what actually caused the date parsing warnings/errors (look at the warnings and errors arrays in $date_errors).
Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]
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
The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:
// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');
Instead of the bulky DateTime object .. just use the core date() function
function isValidDate($date, $format= 'Y-m-d'){
return $date == date($format, strtotime($date));
}
Use it:
function validate_Date($mydate,$format = 'DD-MM-YYYY') {
if ($format == 'YYYY-MM-DD') list($year, $month, $day) = explode('-', $mydate);
if ($format == 'YYYY/MM/DD') list($year, $month, $day) = explode('/', $mydate);
if ($format == 'YYYY.MM.DD') list($year, $month, $day) = explode('.', $mydate);
if ($format == 'DD-MM-YYYY') list($day, $month, $year) = explode('-', $mydate);
if ($format == 'DD/MM/YYYY') list($day, $month, $year) = explode('/', $mydate);
if ($format == 'DD.MM.YYYY') list($day, $month, $year) = explode('.', $mydate);
if ($format == 'MM-DD-YYYY') list($month, $day, $year) = explode('-', $mydate);
if ($format == 'MM/DD/YYYY') list($month, $day, $year) = explode('/', $mydate);
if ($format == 'MM.DD.YYYY') list($month, $day, $year) = explode('.', $mydate);
if (is_numeric($year) && is_numeric($month) && is_numeric($day))
return checkdate($month,$day,$year);
return false;
}
REGEX should be a last resort. PHP has a few functions that will validate for you. In your case, checkdate is the best option. http://php.net/manual/en/function.checkdate.php
Nicolas solution is best. If you want in regex,
try this,
this will validate for, 01/01/1900 through 12/31/2099 Matches invalid dates such as February 31st Accepts dashes, spaces, forward slashes and dots as date separators
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}
This function working well,
function validateDate($date, $format = 'm/d/Y'){
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
I know this is an older post, but I've developed the following function for validating a date:
function IsDateTime($aDateTime) {
try {
$fTime = new DateTime($aDateTime);
$fTime->format('m/d/Y H:i:s');
return true;
}
catch (Exception $e) {
return false;
}
}
Try This
/^(19[0-9]{2}|2[0-9]{3})\-(0[1-9]|1[0-2])\-(0[1-9]|1[0-9]|2[0-9]|3[0-1])((T|\s)(0[0-9]{1}|1[0-9]{1}|2[0-3]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})\:(0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-9]{1}|4[0-9]{1}|5[0-9]{1})((\+|\.)[\d+]{4,8})?)?$/
this regular expression valid for :
2017-01-01T00:00:00+0000
2017-01-01 00:00:00+00:00
2017-01-01T00:00:00+00:00
2017-01-01 00:00:00+0000
2017-01-01
Remember that this will be cover all case of date and date time with (-) character
Not sure if this answer the question or going to help....
$dt = '6/26/1970' ; // or // '6.26.1970' ;
$dt = preg_replace("([.]+)", "/", $dt);
$test_arr = explode('/', $dt);
if (checkdate($test_arr[0], $test_arr[1], $test_arr[2]) && preg_match("/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/", $dt))
{ echo(date('Y-m-d', strtotime("$dt")) . "<br>"); }
else
{ echo "no good...format must be in mm/dd/yyyy"; }
We can use simple "date" input type, like below:
Birth date: <input type="date" name="userBirthDate" /><br />
Then we can link DateTime interface with built-in function 'explode':
public function validateDate()
{
$validateFlag = true;
$convertBirthDate = DateTime::createFromFormat('Y-m-d', $this->birthDate);
$birthDateErrors = DateTime::getLastErrors();
if ($birthDateErrors['warning_count'] + $birthDateErrors['error_count'] > 0)
{
$_SESSION['wrongDateFormat'] = "The date format is wrong.";
}
else
{
$testBirthDate = explode('-', $this->birthDate);
if ($testBirthDate[0] < 1900)
{
$validateFlag = false;
$_SESSION['wrongDateYear'] = "We suspect that you did not born before XX century.";
}
}
return $validateFlag;
}
I tested it on Google Chrome and IE, everything works correctly. Furthemore, Chrome display simple additional interface. If you don't write anything in input or write it in bad format (correctly is following: '1919-12-23'), you will get the first statement. If you write everything in good format, but you type wrong date (I assumed that nobody could born before XX century), your controller will send the second statement.
I think it will help somebody.
function isValidDate($thedate) {
$data = [
'separators' => array("/", "-", "."),
'date_array' => '',
'day_index' => '',
'year' => '',
'month' => '',
'day' => '',
'status' => false
];
// loop through to break down the date
foreach ($data['separators'] as $separator) {
$data['date_array'] = explode($separator, $thedate);
if (count($data['date_array']) == 3) {
$data['status'] = true;
break;
}
}
// err, if more than 4 character or not int
if ($data['status']) {
foreach ($data['date_array'] as $value) {
if (strlen($value) > 4 || !is_numeric($value)) {
$data['status'] = false;
break;
}
}
}
// get the year
if ($data['status']) {
if (strlen($data['date_array'][0]) == 4) {
$data['year'] = $data['date_array'][0];
$data['day_index'] = 2;
}elseif (strlen($data['date_array'][2]) == 4) {
$data['year'] = $data['date_array'][2];
$data['day_index'] = 0;
}else {
$data['status'] = false;
}
}
// get the month
if ($data['status']) {
if (strlen($data['date_array'][1]) == 2) {
$data['month'] = $data['date_array'][1];
}else {
$data['status'] = false;
}
}
// get the day
if ($data['status']) {
if (strlen($data['date_array'][$data['day_index']]) == 2) {
$data['day'] = $data['date_array'][$data['day_index']];
}else {
$data['status'] = false;
}
}
// finally validate date
if ($data['status']) {
return checkdate($data['month'] , $data['day'], $data['year']);
}
return false;
}

Daylight Saving Time (DST) in CakePHP

I'm creating a web application using cakephp 1.2.6. There is a functionality that I need to save the time that user is entered in GMT format. I'm using below method to do this.
function convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Y-m-d H:i:s') {
if (empty($dateTimeStr))
return $dateTimeStr;
else if (empty($fromTimeZone))
return $dateTimeStr;
else {
// Inverse the + or minus. Decimal value should be passed
//$timeHelper = new TimeHelper();
$newTZ = -1 * $fromTimeZone;
return $this->format($format, $dateTimeStr, null, $newTZ) ;
}
}
function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
$date = $this->fromString($date, $userOffset);
if ($date === false && $invalid !== false) {
return $invalid;
}
return date($format, $date);
}
function fromString($dateString, $userOffset = null) {
if (empty($dateString)) {
return false;
}
if (is_int($dateString) || is_numeric($dateString)) {
$date = intval($dateString);
} else {
$date = strtotime($dateString);
}
if ($userOffset !== null) {
return $this->convert($date, $userOffset);
}
return $date;
}
function convert($serverTime, $userOffset) {
$serverOffset = $this->serverOffset();
$gmtTime = $serverTime - $serverOffset;
$userTime = $gmtTime + $userOffset * (60*60);
return $userTime;
}
convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Y-m-d H:i:s') is the method that I'm calling in my code to pass the date time and time zone. I have a combo box of time zones and if user select time zone as "Pacific" it will pass the -8 as the value of $fromTimeZone. But because of the DST this can be changed.
So is there any way in cakephp to find the up to date time zone values automatically and convert the time to GMT?
Once you know the timezone of the user you can get its offset as follows:
$est_tz = new DateTimeZone('America/New_York');
$d = new DateTime("now", $est_tz);
$offset = $est_tz->getOffset($d);

Validate date format in php

I'm trying to validate date using PHP.
I'd like following formats to be valid:
d/m/yy
d/m/yyyy
dd/m/yy
dd/m/yyyy
d/mm/yy
d/mm/yyyy
dd/mm/yy
dd/mm/yyyy
I've tried many regular expressions and different variations of checkdate() function. Currently I have something like this:
function _date_is_valid($str)
{
if(strlen($str) == 0)
return TRUE;
if(substr_count($str,'/') == 2)
{
if (preg_match("/^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2}))/", $str))
{
$datearray = explode('/',$str);
if($datearray[2] > 2030)
return FALSE;
return checkdate($datearray[1], $datearray[0], $datearray[2]);
}
else
{
return FALSE;
}
}
return FALSE;
}
This however, validates dates like 11/11/200 and 11/11/200#
How can I validate date to match required format?
Edit: I could check datearray[2] to be between 10 and 30 and 2010 and 2030. But is there a way to check it using regex?
Edit1: return TRUE on strlen($str) == 0 is because I want users to be able to add events without knowing when will the event occur so someone else can qualify the schedule and assign event to certain date later
Just for the record. I ended up doing:
function _date_is_valid($str)
{
if(strlen($str) == 0) //To accept entries without a date
return TRUE;
if(substr_count($str,'/') == 2)
{
list($d,$m,$y) = explode('/',$str);
if(($y >= 10 && $y <= 30) || ($y >= 2010 && $y <= 2030))
{
return checkdate($m,$d,$y);
}
}
return FALSE;
}
Thanks for all your answers
function _date_is_valid($str) {
if (substr_count($str, '/') == 2) {
list($d, $m, $y) = explode('/', $str);
return checkdate($m, $d, sprintf('%04u', $y));
}
return false;
}
If it will always will be date / month / year you can use checkdate:
function _date_is_valid($str)
{
$array = explode('/', $str);
$day = $array[0];
$month = $array[1];
$year = $array[2];
$isDateValid = checkdate($month, $day, $year);
return $isDateValid;
}
an easy way to do this
<?php
if(!$formated_date = date_create_from_format('Y-m-d',$dateVar))
Try this:
function _date_is_valid($str) {
if (strlen($str) == 0) {
return TRUE;
}
return preg_match('/^(\d{1,2})\/(\d{1,2})\/((?:\d{2}){1,2})$/', $str, $match) && checkdate($match[2], $match[1], $match[3]) && $match[2] <= 2030;
}
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" ;
}
}
?>
What I did to validate it was simple
function dateValidate($pDate) {
if(empty($pDate))
return true;
$chDate = date('Y-m-d', strtotime($pDate));
if($chDate != '1970-01-01')
return true;
else
return false;
}
You can find it out with using regexp too
how about if(strtotime($str) !== FALSE) $valid = TRUE;

Categories