PHP check date difference for backward date - php

I have checked that the input date is a valid date, now need to check for backward date where date_start must be before date_end.
I have tried several other option to no avail, I really dont want to compare the substring of the input if possible.
The input are from html5 date using chrome with format dd/mm/yyyy
class MY_Form_validation extends CI_Form_validation {
public $CI;
public function date_format($date) {
if (($timestamp = strtotime($date)) === false) {
return false;
}
}
//error message stored in caller module language folder
public function backward_date($date_start, $date_end) {
$date_1 = new DateTime($date_start);
$date_2 = new DateTime($date_end);
if ($date_1 > $date_2 == true) {
return false;
}
else {
return true;
}
}
}

try this one
public function backward_date($date_start, $date_end) {
$ts1 = strtotime($date_start);
$ts2 = strtotime($date_end);
$seconds_diff = $ts2 - $ts1;
return ($seconds_diff>0) ? true : false;
}

The problem here is that DateTime is not able to parse the string from 'dd/mm/yyyy' to a valid DateTime Object.
Here is the received error :
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/10/2017)
In order to fix this, you could use the createFromFormat() method from the DateTime model to parse your string with a specified format.
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
So your method would be like :
public function backward_date($date_start, $date_end)
{
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
$date_2 = DateTime::createFromFormat('d/m/Y', $date_end);
return $date_1 <= $date_2;
}
Hope it helps.

Try to this ... Working for me.
function date_calculate($start_date, $end_date) {
$dStart = new DateTime($start_date);
$dEnd = new DateTime($end_date);
$days=0;
if ($dStart < $dEnd) {
$dDiff = $dStart->diff($dEnd);
$dDiff->format('%R');
$days = $dDiff->days;
return $days;
} else {
return $days;
}
}

Related

How to effectively pass data from my controller to repository, Symfony

I'm working on a Symfony project that makes use of a
Repository file in which I have declared and created an instance of a query builder
(repository1)
$mk = $this->createQueryBuilder('up');
$later = date("Y-m-d", strtotime("-3 months"));
$today = date("Y-m-d");
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
automatically this generates data for my page between the above dates.
Now I want to create a form where I can make a search between two dates.
with the intention of passing the posted data from this form to my controller into my method below
My controller below (controller1)
protected function getData(EntityManagerInterface $entityManager,Request $request) {
// this code to get data from repository
$entityManager->getRepository(repository1::class)->getName()
// receive posted data
$date1 = $request->get('date');
$date2 = $request->get('date');
// now how to pass data to my repository1
}
Please how do I edit what I have to post data from within my controller to my (repository1)
so then it would be
$mk = $this->createQueryBuilder('up');
$later = $date1;
$today = $date2;
$mk->andWhere('up.period BETWEEN :start AND :end');
$mk->setParameter('start', $later);
$mk->setParameter('end', $today);
return $mk->getQuery()->getResult();
is this even possible, or im over thinking it?
RepositoryClass
public function getByStartEndDate(DateTimeInterface $start, DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}
Controller Class
private function getData(Request $request, RepositoryClass $repo)
{
// May need to convert these to DateTime objects
$start = $request->get('start');
$end = $request->get('end');
$records = $repo->getByStartEndDate($start, $end);
// do what you want with the records here
}
You can give the dates as parameters to your method.
Controller Class:
protected function getData(EntityManagerInterface $entityManager,Request $request) {
$start = $request->get('start') ? new \DateTime($request->get('start')) : null;
$end = $request->get('end') ? new \DateTime($request->get('end')) : null;
$result = $entityManager->getRepository(Entity::class)->getName($start, $end);
// do with result as desired
}
Repository Class:
public function getName(\DateTimeInterface $start, \DateTimeInterface $end)
{
return $this->createQueryBuilder('up')
->andWhere('up.period BETWEEN :start AND :end')
->setParameter('start', $start)
->setParameter('end', $end)
->getQuery()
->getResult()
;
}

Create a function in codeigniter that returns true if the input datetime is 2days ahead of current datetime, othewise false

I'm new in codeigniter, im trying to create a function that accepts datetime input from a user. If the input is 2 or more days ahead of current datetime, it should return true, if not it should return false.
//my controller looks like this:
public function checkDateTimeInput(){
$dateTimeInput = $this->input->post('dateTimeInput');
if($dateTimeInput /*Greater than 2 days or more*/){
return true;
}else{
return false;
}
}
//in my view:
<?php echo form_open('schedules/checkDateTimeInput'); ?>
<input type="datetime-local" name="dateTimeInput">
<input type="submit" value="submit">
</form>
You could use DateTime() today +2 day to get the next 2 days :
public function checkDateTimeInput(){
$dateTimeInput = new DateTime($this->input->post('dateTimeInput'));
$next_days = new DateTime('today +2 day');
if($dateTimeInput > $next_days) { /*Greater than 2 days or more*/
return true;
}else{
return false;
}
}
You should try this in your controller, The below given code is for 12 hour format
//my controller looks like this:
public function checkDateTimeInput() {
// date_default_timezone_set("Asia/Kolkata"); // make sure you have set it to yours in config file
$date1 = date('Y-m-d h:i:sa', strtotime('+2 days'));
$posted_date_time = date('Y-m-d h:i:sa', strtotime($this->input->post('dateTimeInput')));
if($posted_date_time >= $date1){
//return true;
echo "True";
}
else {
//return false;
echo "False";
}
}

MySQL database and importing dates problems

Okay,so in my mysql database I use a date field. Using PHP I check if the user is 18 years of age or not. Then I try to enter all the form information to my MySQL database to make a user. I keep getting a blank screen (besides my navbar and footer) The user is not being saved into the database, and the error log shows this error: PHP Recoverable fatal error: Object of class DateTime could not be converted to string in ....
$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
$dateObj->format('Y-m-d');
return $dateObj;
}
}
So the question is, do I need to convert the dateTime Obj into a string before MySQL will accept it? The field is set to hold 'dates' so I thought the date obj would be the same thing? How does one change it to a string.
You are returning the DateTime object, because the format function returns a string, it doesn't change the object. Try returning the result of the format function which is the formatted string.
return $dateObj->format('Y-m-d');
$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
return $dateObj->format('Y-m-d');
}
}
If you want a string result, you have to return the format() result, not the object itself.
But the error you have specified is not triggered directly in this code, but somewhere in the else, where you try to convert the result to string.

Codeigniter: date validation

Does anyone know how to validate date. For example, cannot have 30 Feb, and no 31 in certain month so when the user enter the valid it will be rejected. I was think about a call back function but not sure how it will be done.
Create a call back function using PHP checkdate function
Use this guide to create callback functions in Codeigniter.
try this the code also takes leap year into account
function valid_date($date)
{
$pattern = '/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?: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]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/';
if(preg_match($pattern, $date) )
{
return true;
}
else
{
$this->form_validation->set_message('valid_date', 'The %s is not valid it should match this dd/md/yyyy format');
return false;
}
}
//and just use this to set rules
$this->form_validation->set_rules('Your date field from html', 'date', 'required|callback_valid_date');
You can use simple regex to validate the date in dd-mm-yyyy format
$this->form_validation->set_rules('dob', 'Date in dd-mm-yyyy',
'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]');
for validation using callback this will make sure of month Feb which is 28 days use this
//Add a rule for validation
$this->form_validation->set_rules('dob', 'Date of Birth', 'callback_valid_date');
//Define a callback and pass the format of date
public function valid_date($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
//Check for valid date in given format
if($d && $d->format($format) == $date) {
return true;
} else {
$this->form_validation->set_message('valid_date',
'The %s date is not valid it should match this ('.$format.') format');
return false;
}
}

Is it possible to change the system date for php (only)

Is it possible to change the system date for php (only).
I want this for debugging/testing purpose.
//Test 1 (2010-01-01)
$datetime = new DateTime(); //(2010-01-01)
//Test 2 (2010-02-01)
$datetime = new DateTime(); //(2010-02-01)
I can't really change the real system clock, because other developers are working on the same system (well I could but still).
I'm just hoping this is possible, or that someone knows a nice trick.
When I print the phpinfo(); I see the following line:
Timezone Database internal
Maybe it's changeable to something like "manual" and ad a timezone with +120
Thanks!
This sounds like an encapsulation issue -- why not search for all mentions of date() or time() and replace them with $site->getDisplayedDate(), or something else appropriate to your code?
I feel your pain, but I don't think there's any way to do this. Think about it this way... how would you feel if, in some unrelated code, you called time() and it gave you some date 3 weeks in the future?
You can change only timezone (and ofcourse only couple hours forward / backward; and not whole day forward), but thats not correct solution...
You could create your own DateTime class that extends the default DateTime and hence change the behaviour:
<?php
class CustomDateTimeVariables {
public static $date = 'now';
}
class CustomDateTime extends DateTime {
public function __construct($time = null, DateTimeZone $timezone = null) {
if ($time === null) {
$time = CustomDateTimeVariables::$date;
}
if ($timezone !== null) {
parent::__construct($time, $timezone);
} else {
parent::__construct($time);
}
}
}
CustomDateTimeVariables::$date = '2010-01-01';
$datetime1 = new CustomDateTime();
CustomDateTimeVariables::$date = '2010-01-02';
$datetime2 = new CustomDateTime();
var_dump($datetime1->Format('Y-m-d H:i:s')); //"2010-01-01 00:00:00"
var_dump($datetime2->Format('Y-m-d H:i:s')); //"2010-01-02 00:00:00"
?>
DEMO
This way you can also set the default time very easily (check CustomDateTimeVariables):
<?php
class CustomDateTimeVariables {
public static $date = 'now +120 hours';
}
class CustomDateTime extends DateTime {
public function __construct($time = null, DateTimeZone $timezone = null) {
if ($time === null) {
$time = CustomDateTimeVariables::$date;
}
if ($timezone !== null) {
parent::__construct($time, $timezone);
} else {
parent::__construct($time);
}
}
}
$datetime = new CustomDateTime();
var_dump($datetime->Format('Y-m-d H:i:s')); //"2013-10-29 13:37:39"
?>
..and when it goes live, you can simply change the default back to now.

Categories