PHP form, checking 2 dates aren't too far apart - php

I've been thrown in at the deep end at work, I grew up knowing plain HTML (mid-90's) and I've been asked to alter a form at work that's in PHP, I can alter PHP code written by others, but there's no way I could write it myself. I've altered this form to just about how I want it, but there's 1 bit I want to alter, if anyone can help it would be greatly appreciated...
been on this for 2 days searching the web and trying stuff, I have the following
<p class="quest">Date from: <input type="text" name="acc2" class="tcal" value="" /> to: <input type="text" name="acc3" class="tcal" value="" />
it uses javascript to pop up a calendar (tigra calendar) that then returns 2 dates (acc2 and acc3), the dates are in d/m/Y (DD/MM/YYYY) format (standard here in Europe/Aus/NZ).
What I'm wanting to do is get it to check if the difference is greater than 42 days (6 weeks), if it is I want it to display some text with a link (42 days or less is fine).
If I put on the page as a test:
<?php echo($acc3); ?>
then it displays 1341442800 on the page (before a date is chosen), if the user selects a date then the above number stays (not dynamic)
Is what I'm wanting possible?
If not, can it be checked on submission and pop up an alert (without the link)?
I currently use Javascript to check the form, an example is:
<script language="javascript" type="text/Javascript">
<!--
function collect() {
if(document.all.ct.value == "TempAcc")
{
if(document.all.acc7.value.length <11)
{
alert("You need to fill in your contact number with your FULL number including STD code.");
return false;
}
}
}//end function collect
//-->
</script>
any help with this would be very much appreciated, please try to be specific with any code as I'm am still very much a beginner.
Thanks in advance.

That works for me: Live demo on fiddle.net
// parse dates from DD/MM/YYYY to YYYY/MM/DD
var oldBegin = parseDate("03/06/2012");
var oldEnd = parseDate("07/06/2012");
// calculate difference and format to days
var diff = Math.round((oldEnd - oldBegin)/1000/60/60/24);
alert(diff);
function parseDate(str) {
var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
Edit:
Include jQuery to your webpage. It will help you with the javascript part.
Give both of your input-fields a unique id (like id="date1" and id="date2") and then get the values in javascript
$('date1').val();
$('date2').val();
The whole code should look something like that:
<script type="text/javascript">
//The code will trigger when the user leaves the second input field
$("#date2").focusout(function() {
// parse dates from DD/MM/YYYY to YYYY/MM/DD
var date1 = parseDate($('date1').val());
var date2 = parseDate($('date2').val());
// calculate difference and format to days
var diff = Math.round((date2 - date1)/1000/60/60/24);
alert(diff);
function parseDate(str) {
var m = str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
});
</script>
You can now add some if-statements to check if one input is empty.

Here's two questions/answers written in PHP and Javascript
PHP
$date1 = "2007-03-24";
$date2 = "2009-06-26";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
Javascript
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);

Try this :
<script type="text/javascript">
function daysBetween() {
var one = new Date(2012, 0, 1); // YYYY - MM - DD
var two = new Date(2012, 5, 5); // YYYY - MM - DD
var one_day=1000*60*60*24
document.write(Math.ceil((two.getTime()-one.getTime())/(one_day))+" days")
}
</script>

Related

How to make Javascript use time from the world clock (GMT to be specific)

I am trying to create a Javascript clock that will display the current Actual time, rather than displaying the local time of the client machine.
The clock is part of a script which calculates the difference in time between two values (in php but the purpose of this clock is to give a visual representation). It is important that the user of the script cannot change the time that is displayed as this will produce incorrect results for the outcome of the whole program.
I realise that i may have to use a php function to return the time in a particular time zone but i do not understand how to input this into my script. My Javascript clock code is below (currenttime_large is the ID of the DIV container of this script) :
<script type="text/javascript" language="javascript">
function renderTime() {
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('currenttime_large');
myClock.textContent = h + ":" + m + ":" + s + " ";
myClock.innerText = h + ":" + m + ":" + s + " ";
}
renderTime();
</script>
Please could someone advise how this script can be adjusted so that the clock which is displayed, displays GMT(London) time rather than the client time.
Many thanks in advance,
Aidan
Use the getUTC... methods:
var h = currentTime.getUTCHours();
var m = currentTime.getUTCMinutes();
var s = currentTime.getUTCSeconds();
I've been looking over something like this,
The best solution I've found is this
http://www.jqueryscript.net/demo/jQuery-Based-Analog-And-Digital-World-Clock-jClocksGMT-js/
If you want you can save the whole page, or download necessary files if they not saved automatically. Then in your html code you just change the GMT timezone according to ID.
That's it
I was searching of world analog clock. i found one source/example which is basically cretated with jQuery, Html 5, CSS 3 and canvas.
Source : https://github.com/php-dedicated-developers/world-clock
It can be done without PHP. I ve done it using simple HTML and JavaScript calculations.
Note: This clock IS NOT UNIVERSAL.
Because i live in india, i fixed all parameters according to Indian GMT (5:30).
If someone wants to use it who does not live in India will have to customize parameters according their own country GMT
How my code works? Here is your answer
First we have created a simple timer program.
Passed the time argument to a function called london()
3.in function london() everything is processed. I have put GMT of India. using the parameters function london is producing correct London time from Indian time and given GMT time
Note:
1. As this code is not universal.. people out of India will have to customize it as they want...
2.This code uses device time and processes correct GMT 0 time. Example my code works substracting 5 hours and 30 minutes from device time because my GMT is 5:30 (India)
3.Will work fine offline
4.If someone changes country(GMT) they will have to customize code again
Full Code
<body onload="timer()">
<p id="txt1"></p>
<p id="txt2"></p>
<script>
function timer(){
//Getting Device Time
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//Returning value of ckeckTime();
m = checkTime(m);
h = checkTime(h);
s = checkTime(s);
var trigger = setTimeout(timer,1000);
document.getElementById("txt1").innerHTML = h+" "+m+" "+s;
london(h,m,s); //Passing device time to function london
}
function london(h,m,s){
//This function produces london time
//var h (Device hour)
// m (Device minute)
// s (Device second)
defhr = 5; //define hour
defmn = 30; //define minutes
/* defhr = 5 and defmn = 30 according to India GMT +5 30*/
if(m < defmn){ //When device minute is less than define minutes
defhr += +0
var hour = h - defhr;
let x = m - defmn;
var min = 60 + x;
} else {
defhr += -1
var hour = h - defhr;
var min = m - defmn;
}
if(h < defhr){ //When device hour is less than define hour
let y = defhr - h;
var hour = 24 - y;
}else {
var hour = h - defhr;
}
// returning value of checkTime();
hour = checkTime(hour);
min = checkTime(min);
document.getElementById("txt2").innerHTML = hour+" "+min+" "+s;
}
//checkTime function adds 0 in front a number when it is less than 10
function checkTime(i){
if(i<10){ i="0"+i; }
return i;
}
</script>
</body>
</html>
Tip:
1. If you live in western countries or GMT value is negative then put negative value in defhr and defmn section.
If anyone is using this code in GMT + 5:30 (India)
They will not need customization.
Make sure your code is producing correct London GMT time.. Grab notebook,calculator or you can test it with online world clock too

Days between two dates in Javascript or Jquery

I want some calculation with Javascript or jquery. actually I have two inputs with date picker. I want when I selected dates in both field a new field value should appear which will have the total number of days for selected date. For example:
I select in input one : 2012-01-01
and
I select in input two: 2013-01-01
then in field three value should be = 365 Days
Hope you understand.
I know how to count days between two dates:
$days = (strtotime($termi_date) - strtotime($str_date)) / (60 * 60 * 24);
echo $days;
var from_date = $("#from_input").datepicker('getDate'),
to_date = $("#to_input").datepicker('getDate');
var diff_in_milliseconds = to_date.getTime() - from_date.getTime();
or simply
diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
DEMO

GMT Time format to integer format

I am trying to show ticker clock for different timezone. When I looked around the web, it looks like it takes number for the offset(for example +5.5 hours) in javascript. But the way we are getting the gmtformat is +05:30 in php which I am trying to feed in to the javascript function. Is there any function that I can use to convert?
/*CLOCK CODE IN JAVASCRIPT*/
function startclock(field, timediff, newOrRepeat)
{
var clockAction=newOrRepeat;
if (timediff=="") {$(field).html("-------");return false;}
/****THERE ARE MORE STUFF IN BETWEEN AND AFTER WHICH IS NOT RELEVANT TO OFFSET****/
var secondsDiff=0;
var secondsTimeZone = 0;
//calculate the difference in time set by both the timezone as well as the DST
secondsTimeZone = parseInt(timediff);
if ($("input[name='daylight']:checked").val()=="on" && $(field).siblings("#isDaylight").val()=="no")
secondsDiff=secondsTimeZone + 3600;
else if ($("input[name='daylight']:checked").val()=="off" && $(field).siblings("#isDaylight").val()=="yes")
secondsDiff=secondsTimeZone - 3600;
else
secondsDiff = secondsTimeZone;
var thetime=new Date();
thetime.setUTCSeconds(parseInt(thetime.getUTCSeconds())+parseInt(secondsDiff));
var nhours=thetime.getUTCHours();
var nmins=thetime.getUTCMinutes();
var nsecn=thetime.getUTCSeconds();
}
I am getting getting gmt format straight from php which i am passing to this function.
function convert_time($time){
$parts = explode(':', $time);
return $parts[0] + number_format($parts[1]/60, 2);
}

Date Calculation

i have a form with a fix date and time entry. (eg: 23:30 - 04/14/2011)
i have a second time entry. (eg: 00:15 - the Next Day)
how can i calculate the Date of the second entry time.
with only on these 3 variables.
Time A = 23:30 on the 04/14/2011
Time B = 00:15 on the ____ ?
Can anyone show me the semantics of this calculation how to find the Date of Time B!
Thanks
I can see a couple of ways of doing this. I would probably do something like this:
In HTML (missing form controls, labels etc):
<input name="date_from" type="text"> <!-- use some sort of javascript date popup control to format this properly-->
<input type="text" name="hours_to"> <!-- remember to add validation to input -->
<input type="text" name="mins_to"> <!-- remember to add validation to input -->
<select name="day_to">
<option value="0">The same day</option>
<option value="1">The next day</option>
<option value="2">The day after that</option>
</select>
Then in your PHP form handler, assuming date_from is in a valid date format:
$time_from = strtotime($_POST['date_from']);
$time_to = str_to_time('Y-m-d 00:00:00', $time_from) //start of the day
+ 86400 * (int) $_POST['day_to'] //86400 seconds in a day
+ 3600 * (int) $_POST['hour_to'] //3600 seconds in an hour
+ 60 * (int) $_POST['min_to']; //60 seconds in a minute
$sql_from = date("Y-m-d H:i:s", $time_from);
$sql_to = date("Y-m-d H:i:s", $time_to);
Then you can do your db insert, subject to validations etc of course.
Also, strtotime() can accept relative time parameters (e.g. '+ 1 day') which might be another way of doing this, check the PHP manual for more info
var date1 = '23:30 - 04/14/2011';
var date2 = '00:15 - the Next Day';
var d1month = date1.split(' - ')[1].split('/')[0];
var d1day = date1.split(' - ')[1].split('/')[1];
var d1year = date1.split(' - ')[1].split('/')[2];
var d1hour = date1.split(' - ')[0].split(':')[0];
var d1min = date1.split(' - ')[0].split(':')[1];
var d2hour = date2.split(' - ')[0].split(':')[0];
var d2min = date2.split(' - ')[0].split(':')[1];
var d = new Date(d1year, parseInt(d1month)-1, d1day, d1hour, d1min, 0, 0);
var d2 = new Date(d1year, parseInt(d1month)-1, parseInt(d1day)+1, d2hour, d2min, 0, 0);

How to make a countdown using PHP

Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;
Time left until the wedding: X months, X days, X hours.
I would preferebly like to do this using php, but would be open to other suggestions.
if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.
The wedding is on Saturday 30th July.
If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.
If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.
Personally I would go for something already implemented, like that small script.
Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.
You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.
Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
// 1. JavaScript
// var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// 2. PHP
var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
var now = <?php echo time() ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
// 1. JavaScript
// var now = new Date().getTime();
// 2. PHP
now = now + 1000;
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
For Static Countdown :
<?php
//A: RECORDS TODAY'S Date And Time
$today = time();
//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);
//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);
//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";
?>
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
Code top by user Neil E. Pearson didnĀ“t work, he forgot to write there the brackets (), working solution is:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
$Target_Date = 1699458858; //expire data
$Time_Left = $Target_Date - time();
$days = floor($Time_Left / (60*60*24));//day
$Time_Left %= (60 * 60 * 24);
$hours = floor($Time_Left / (60 * 60));//hour
$Time_Left %= (60 * 60);
$min = floor($Time_Left / 60);//min
$Time_Left %= 60;
$sec = $Time_Left;//sec
echo "$days days and $hours hours and $min min and $sec sec left";
I would not use php (serverside) for this. Because you need to refresh your page every time to see the counting. Preferably use javascript (clientside) for this, more specific jquery (javascript framework). And look for a jquery plugin such as: http://keith-wood.name/countdown.html
If you want something realtime, you'll need to use client-side scripting, namely JavaScript.
You can do it in PHP, but it won't "animate":
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
You could put some more math in for months, but it gets fuzzier because a month isn't a fixed amount of time.
The other way would be to use the date() function to pick out the individual elements (hour, minute, second, day, month etc) and use rollover math, but it's a lot of bother for a 'nice effect'.
Let me know if you want a JavaScript example. Don't bother with jQuery - it's a canon for killing a mosquito :)
try this
<?php
$target = mktime(0, 0, 0, 9, 25, 2011) ;//set marriage date
$today = time () ;
$difference =($target-$today) ;
$month =date('m',$difference) ;
$days =date('d',$difference) ;
$hours =date('h',$difference) ;
print $month." month".$days." days".$hours."hours left";
?>
Try this
$wedding = strtotime("2014-02-20 12:00:00"); // or whenever the wedding is
$current=strtotime('now');
$diffference =$wedding-$current;
$days=floor($diffference / (60*60*24));
echo "$days days left";
Try this static countdown.
<?php
//Current Date And Time
$todaytime = time();
//Set Date And Time OF The Event
$eventdate = mktime(0,0,0,0,28,2021);
//Calculate Days Until The Event
$countdown = round(($eventdate - $todaytime)/86400);
//Display Countdown
echo "$countdown days until the event";
?>

Categories