开发者

Dates difference with php

开发者 https://www.devze.com 2022-12-13 02:01 出处:网络
Hi guys I was wondering if anyone could help me with the following: I have two dates entered in two different fields > startDate and endDate.

Hi guys I was wondering if anyone could help me with the following:

I have two dates entered in two different fields > startDate and endDate.

As they are entered I would like to show a warning开发者_JAVA百科 if:

  • the second one is a date before the first one. So it is wrong.
  • and that between the first one and the second one there a minimum gap of at least 3 days during certain period of the year and 7 days during other periods of the year.

I was thinking to write a PHP function but how do I call it as soon as the second date is entered?

Many many thank for you help Francesco


Convert your dates to Julian day with gregoriantojd.

/**
 * Get the Julian day of a date. The Julian day is the number of days since
 * January 1, 4713 BC.
 */
function datetojd($date)
{
    return gregoriantojd(idate('m', $date),
                         idate('d', $date),
                         idate('Y', $date));
}

// you can use strtotime to parse a lot of date formats, assuming they are text
$startDate = strtotime('22nd Nov 2009');
$finishDate = strtotime('26nd Nov 2009');

$diff = datetojd($finishDate) - datetojd($startDate);

if ($diff < 0) {
    // oops, $finishDate is before $startDate
}
else {
    // check $diff is at least 3 or 7 depending on the dates
}


Do the check on the client side with Javascript.

Then perform the same checks server side which can present a message after the form has been submitted (for those few users running with Javascript disabled?).


I'm not sure if you can call it as soon as the second date is entered, unless you reload the page or have the function on another page which could get a tad complicated

The way i would check the dates is to use php's mktime function, which will give you the unix time. Then if the second one is less that the first, the second date is before and if the second one is less that the first + 3 * 24 *60 * 60 (seconds in 3 days) then it isn't 3 days apart


1° case:

SELECT [whatever you need from the table] WHERE endDate < startDate

2°case:

SELECT [whatever you need from the table] WHERE (endDate - startDate) >= IF([select that define in wich period of the year the data are],3, 7)

This ill do the trick, but probably your problem cant be solved sql-side.

Please, describe better what you need to do.

EDIT:

Ok, then as someone else suggested, first check htem by js (for convenience, not for safely: never rely only on js validation!)

Use strtotime for the comparison/operation.

EDIT2 (last;) : Go with Alex's Answer

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号