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);
Related
Hi I am new to javascript and php. I have a form that has three text boxes, starttime, endtime and results. I am trying to take the starttime and endtime and find how much time has passed and display this in the results. How can I go about this?
here is my html:
<form action="JobChangeTimeSheet.php" method="GET">
Machine Stopped at:
<input type="time" name="start_date"/>
End of TO:
<input type="time" name="since_start"/>
<input type="submit">
Total time
<?PHP
if (! empty($_GET['start_date'])){
$start_date = new DateTime($_GET['start_date']);
$since_start = $start_date->diff(new DateTime($_GET['since_start']));
echo $since_start->days.' days ';
echo $since_start->h.' hours';
echo $since_start->i.' minutes';
}
?>
</form>
You can see there are 2 text boxes, a button, and a third disabled text box. I am trying to view the difference in minutes between the two text boxes in the third text box
Since you do not have a code I can work on, I will guide you exactly through the steps on how to do this.
Load your HTML input in PHP vars named $start_date and $end_date. Use these lines:
$start_date = new date("Y-m-d H:i:s",strtotime($start_date));
$end_date = new date("Y-m-d H:i:s",strtotime($end_date));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Difference in minutes is: '.($hours * 60 + $minutes);
PS: You are talking about Javascript in your question but no Javascript code has been presented in your code. Are you using some sort of DateTimePicker?
Timer Main
$curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));
$timecountdownend = strtotime($curDate) + strtotime("+1 hours");
$timecountdownstart = strtotime("-8 hour");
$timeleft = $timecountdownend - $timecountdownstart;
if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
echo $timeleft;
}
?>
Timer Update 5 Seconds
$(document).ready(function(){
var timerText = $("[timer]");
setInterval(function(){
$.post("timer.php", {type: "timerupdate"}, function(data){
timerText.html("Time Left:" + data + " seconds timer.")
});
}, 5000);
});
WHAT ARE YOU TRYING TO ACHIEVE?
The idea is when a user reserves an item, expiration date is set into the database so that the USER that reserved the item cannot hold it forever. So for example:
User A: Reserve Item A.
[SERVER] $database->insert("reservation", $curDate);
[SERVER] 2016-04-03 16:00:00 (After 30 minutes this item is expired)
That what's supposed to happen in the back-end.
WHAT HAVE YOU TRIED?
I've done tons of googling to see how I could add x hours or minutes to the current date and pass that on to become a unix timestamp.
WHAT IS YOUR PROBLEM?
Whenever I try the code above it works but doesn't come up with the right output I need. Specifically the problem is at $timecountdownend = strtotime($curDate) + strtotime("+1 hours");
** NEW **
date_default_timezone_get("America/New York");
$curDate = date("Y-m-d H:i:s", strtotime("-8 hours"));
$date = new DateTime($curDate);
date_add($date, date_interval_create_from_date_string('2 hour'));
$timecountdownend = strtotime($date->format('Y-m-d H:i:s'));
$timecountdownstart = strtotime("-8 hour");
$timeleft = $timecountdownend - $timecountdownstart;
if (isset($_POST['type']) && $_POST['type'] == "timerupdate") {
echo $timeleft;
}
OUTPUT: 7200 seconds (STUCK though). It's precise but it's not counting down.
Did you consider http://php.net/manual/en/datetime.add.php ?
the only tricky part is to understand how this syntax work : $date->add(new DateInterval('P7Y5M4DT4H3M2S')); P7 means add 7 years H3 means add 3 hours
Once you save or update the date in your database, send a copy along with the response and in your final response document put this :
https://jsfiddle.net/o740okn4/5/
You will need to make these calls from CDN or get the scripts from git
moment.min.js
moment-duration-format.min.js
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js
and
https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js
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
I have a script that was working, well is working but not properly. The function is suppose to work out the time difference between two dates/times.
The First date is the Current Date and Time (Date + Hr:Min) and the second date is chosen by a user.
The purpose is to show error when the current date/time is within 24 hours from the user chosen date. i.e. if today is 23/20/2012 16:00 and the user chooses 24/10/2012 15:00 (this mean its within 24 hours) but if user chooses 26/10/2012 19:00 then its passed 24 hours.
Now this works fine but when the date changes its year (when user selected any date after 31st Dec 2012.. it assumes its still within 24 hours.. and im quite baffled how this happens.. can anyone shed some light what I've done wrong?
$dt = $_GET['dt']; $tm = $_GET['tm'];
// Current Date an time (Hrs & Mins)
$date1 = date("Y-m-d H:i");
// Chosen Date/Time
$date2 = date("Y-m-d", strtotime( "$dt" ) );
$diff = strtotime($date2." $tm") + - strtotime($date1);
if($diff/3600 < 24)
echo "0";
else
echo "1";
The following is the corresponding Ajax that makes th call
function getAjaxTime()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
dt = document.frm.arrival_date.value;
tm = document.frm.arrival_hour.value +':'+document.frm.arrival_min.value;
xmlHttp.open("GET","<?php echo $base_dir;?>/admin/get/timediff.php?dt="+encodeURI(dt)+"&tm="+encodeURI(tm),false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
I would try something like this:
function isDateWithin24Hours($targetDate, $currentDate = 'now') {
$targetDate = new DateTime($targetDate);
$currentDate = new DateTime($currentDate);
$interval = $targetDate->diff($currentDate);
//%a = total number of days
if ($interval->format('%a') > 1) {
return (int) false;
}
return (int) true;
}
echo isDateWithin24Hours('2012-10-24 19:00:00');
echo isDateWithin24Hours('2012-10-24 19:00:00', '2012-10-23 18:00:00');
According to the php manual - http://us3.php.net/manual/en/datetime.formats.date.php - your date is not a valid format:
24/10/2013 // with / as deliminators
These would be valid
24-10-2013 // with - as deliminators
10/24/2013 // with / as deliminators and as m/d/Y
Update-
Also, the following format is invalid in strtotime & date-
Thursday, 10 May, 2012 00:30
But this would be valid -
Thursday, May 10, 2012 00:30
Update #2
In fact once your $_GET['dt'] is in a valid php format, you could simplify your code to-
$dt = $_GET['dt']; $tm = $_GET['tm'];
// Current Date an time (Hrs & Mins)
$date1 = date("Y-m-d H:i");
$diff = strtotime($dt." ".$tm) + - strtotime($date1);
if($diff/3600 < 24)
echo "0";
else
echo "1";
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>