Bootstrap Datetimepicker Remaing Number of Seconds - javascript

I am creating task again service and each service has number of hours
so when i log manually log time i want datetimepicker to only log reaming number of seconds
EX:
Step 1. service contain 2hr
Step 2. I logged 1hr
Step 3. Now I want to add validation that user should only add reaming time in datetimepicer(1hr)
Here is my code
<script type="text/javascript">
var timezone_offset_minutes = Intl.DateTimeFormat().resolvedOptions().timeZone;
$('#timezone').val(timezone_offset_minutes);
$('#startTime, #endTime').timepicker({
minuteStep: 1,
showSeconds: true,
secondStep: true,
}).on('hide.timepicker', function (e) {
calculateTime();
});
jQuery('#start_date, #end_date').datepicker({
autoclose: true,
todayHighlight: true,
}).on('hide', function (e) {
calculateTime();
});
calculateTime();
function calculateTime() {
var startDate = $('#start_date').val();
var endDate = $('#end_date').val();
var startTime = $("#startTime").val();
var endTime = $("#endTime").val();
var timeStart = new Date(startDate + " " + startTime);
var timeEnd = new Date(endDate + " " + endTime);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
var seconds = Math.floor(minutes * (60));
var calSeconds = seconds % 60;
if (hours < 0 || minutes < 0) {
var numberOfDaysToAdd = 1;
timeEnd.setDate(timeEnd.getDate() + numberOfDaysToAdd);
var dd = timeEnd.getDate();
if (dd < 10) {
dd = "0" + dd;
}
var mm = timeEnd.getMonth() + 1;
if (mm < 10) {
mm = "0" + mm;
}
var y = timeEnd.getFullYear();
$('#end_date').val(mm + '/' + dd + '/' + y);
calculateTime();
}
else {
$('#total_time').html(hours + " Hours " + Math.floor(minutes) + " Minutes " + calSeconds + " Seconds ");
}
}
</script>
and here is remaing number of seconds i am getting from controller
{{$subsSeconds}} //9 seconds

If I were you, I wouldn't validate these things in javascript, since this is executed on the user's computer, but in PHP on your server.
Since you're using PHP, you could use the PHP date() functions, or use an external library to calculate if the given date is past a certain point.
If you really want to do date calculations in javascript, Moment.js (https://momentjs.com/) is a pretty good javascript library for dealing with dates. Since plain old javascript isn't very good for dealing with dates (in my opinion).

Related

Getting issue while calculating the time difference using JavaScript

I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}
Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.

Moment.js format difference

In one of my projects i have to calculate the difference between two times. For example the work hours starts at 6:30 and finishes at 10 o'clock. The difference is 3 hours and 30 minutes. I write a small JS function to handles the task and it works great, gives me the following result: 3.5.
I tried .format("HH:mm") but the result was undefined not a function.
Is there any method that converts the output like "HH:mm"?
Here is the dateDiff function:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.asHours();
console.log(hours);
document.getElementById('dateDiffResult').value = moment(hours);
}
You could just get the hours and minutes separately and format the string:
function dateDiff() {
var startTime = moment(document.getElementById("startTime").value, "HH:mm");
var endTime = moment(document.getElementById("end").value, "HH:mm");
var duration = moment.duration(endTime.diff(startTime));
var hours = duration.hours();
var minutes = duration.minutes();
document.getElementById('dateDiffResult').value = hours +":"+ minutes;
}
if your function works and gives you the time difference in hours, surely it is then simple to calculate the hours and minutes from the number of hours? Using your stated difference of 3.5...
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//pads the hours with a leading zero if required to give hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//pads the minutes with a leading zero if required to give minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
I added the following to demonstrate this in the snippet:
$(document).ready
(function(){
var diff=3.5;
var hour=Math.floor(diff);//gives hour=3;
var hours=("0"+ hour).slice(-2);//gives hours=03;
var minute = (diff-hour)*60;//gives 30
var minutes=("0"+ minute ).slice(-2);//gives minutes=30;
var totalDiff= hours + ":" +minutes; //gives 03:30 as in HH:MM
alert("HH:MM: " + totalDiff);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Using a time-field jQuery plugin, you can generate time fields. After that, you can listen to changes to the fields and update the hours difference accordingly.
(function($) {
$.initTimeFields = function(interval) {
$('.time-field').each(function(_, field) {
$(field).initTimeField(interval);
});
};
$.fn.initTimeField = function(interval) {
var hour = 0, minute = 0, diff;
while (hour < 24 && minute < 60) {
this.append($('<option>', {
val : hour * 60 + minute,
text : ('00' + hour).substr(-2) + ':' + ('00' + minute).substr(-2)
}));
minute += interval;
diff = minute - 60;
if (diff >= 0) {
hour += 1;
minute %= 60;
}
}
var value = this.data('value') || 0;
if (typeof value === 'string' && value.indexOf(':') > -1) {
value = (function(values) {
return parseInt(values[0], 10) * 60 + parseInt(values[1], 10);
}(value.split(':')));
}
this.val(value);
};
}(jQuery));
function updateTimeDiff() {
$('#hour-diff').val(calcHourDiff(getTime('#start-time'), getTime('#end-time')) + ' hours');
}
function calcHourDiff(startTime, endTime) {
var diff = moment.duration(endTime.diff(startTime));
return ('00' + diff.hours()).substr(-2) + ':' + ('00' + diff.minutes()).substr(-2);
}
function getTime(selector) {
return moment($(selector).find('option:selected').text(), "HH:mm");
}
$('.time-field').on('change', function() {
updateTimeDiff()
});
// Main
$.initTimeFields(15);
$('.time-field').trigger('change');
label { display: inline-block; width: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<label>Start: </label><select id="start-time" class="time-field" data-value="06:30"></select><br />
<label>End: </label><select id="end-time" class="time-field" data-value="10:00"></select><br />
<label>Diff: </label><input id="hour-diff" type="text" size="8" />

jQuery multiple clocks in one page

I (a javascript newbie) want to have mutiple clocks with different time values in one page.
I managed to get the clock running, but if i add a second clock only one clock is getting displayed. In the console both ids with the correct (different) time are printed.
(function($, undefined) {
$.fn.clock = function(currentTime) {
return this.each(function() {
var localTime = +Date.now();
var timeDiff = currentTime - localTime;
updateClock = function (self, diff) {
var realtime = +Date.now() + diff;
var date = new Date(realtime);
var hours = date.getHours();
if(hours < 10) hours = "0"+hours;
var minutes = date.getMinutes();
if(minutes < 10) minutes = "0"+minutes;
var seconds = date.getSeconds();
if(seconds < 10) seconds = "0"+seconds;
var day = date.getDate();
var month = date.getMonth()+1;
var year = 1900 + date.getYear();
if(day < 10) day = "0"+day;
if(month < 10) month = "0"+month;
var formattedTime = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ':' + seconds;
self.text(formattedTime);
console.log(self.attr("id")+":"+formattedTime);
setTimeout(function() {updateClock(self, diff)}, 1000);
};
updateClock($(this), timeDiff);
});
};
return this;
})(jQuery);
Call (takes time in ms as parameter):
<script type="text/javascript">
$(document).ready(function() {
$("#clock").clock(123456789);
$("#clock2").clock(1234567899);
});
</script>
clock and clock2 are empty divs.
Problem: Only clock2 (the last initialized clock) is displaying the time.
EDIT:
DIVs:
<div id="clock"/>
<div id="clock2"/>
EDIT2:
It's working now. The divs need an end-tag.
updateClock is a implicitly global variable. Add a var, or make it
function updateClock(self, diff) {
to scope the function correctly.
Div's must have end tag
Tag omission None, both the starting and ending tag are mandatory.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
<div id="clock"></div>
<div id="clock2"></div>

Javascript: Adding digits without Sum?

I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()

How to keep updating datetime every minute in Javascript?

I am using following code to display date on my webpage. I need to update it every minute. How to do that?
var d=new Date();
var n=d.toString();
document.write(n);
Currently its static, means when the page load, datetime of that moment is displayed. I have to update time every minutes without refreshing the page.
Try with setInterval(): http://jsfiddle.net/4vQ8C/
var nIntervId; //<----make a global var in you want to stop the timer
//-----with clearInterval(nIntervId);
function updateTime() {
nIntervId = setInterval(flashTime, 1000*60); //<---prints the time
} //----after every minute
function flashTime() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time); //<----updates the time in the $('#my_box1') [needs jQuery]
}
$(function() {
updateTime();
});
You can use document.getElementById("my_box1").innerHTML=time; instead of $('#my_box1')
from MDN:
About setInterval : --->Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
About setTimeout : ----> Calls a function or executes a code snippet after specified delay.
Here is how you can print date time every second
function displayDate()
{
var n=BuildDateString();
document.write(n);
window.setTimeout("displayDate();", 1000); // to print it every minute take 1000*60
}
function BuildDateString()
{
var today = new Date()
var year = today.getYear()
if (year < 2000)
year = "19" + year
var _day = today.getDate()
if (_day < 10)
_day = "0" + _day
var _month = today.getMonth() + 1
if (_month < 10)
_month = "0" + _month
var hours = today.getHours()
var minutes = today.getMinutes()
var seconds = today.getSeconds()
var dn = "AM"
if (hours > 12)
{
dn = "PM"
hours = hours - 12
}
if (hours == 0)
hours = 12
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
var DateString = _month+"/"+_day+"/"+year+" "+hours+":"+minutes+":"+seconds+" "+dn
return DateString;
}
I am using following approach:
var myVar=setInterval(function(){myDateTimer()},60000);
function makeArray()
{
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}
function myDateTimer()
{
var months = new makeArray('January','February','March','April','May',
'June','July','August','September','October','November','December');
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var finaldate = days[ date.getDay() ] + ", " + months[month] + " " + day + ", " + year + " " + hours +" : " + minutes;
document.getElementById("showDateTime").innerHTML=finaldate;
}
just do this
$(function(){
setInterval(function(){
var d=new Date();
var n=d.toString();
$('#test').html(n);
},1000);
});
demo http://runjs.cn/code/txlexzuc

Categories