1.
Ok, for the first question I have a question about Moment. It doesn't calculate the time right(I think?)
This is my script:
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// breaking hours and minutes. needed format: HH:mm
var startHours = originalStartTime.substring(0, 2).replace(':', ''),
startMinutes = originalStartTime.substring(3, 5),
endHours = originalEndTime.substring(0, 2).replace(':', ''),
endMinutes = originalEndTime.substring(3, 5);
// momentJs variables
var mStart = moment().hour(startHours).minute(startMinutes),
mEnd = moment().hour(endHours).minute(endMinutes),
mBreak = moment.duration(originalBreakTime);
var result = moment( mEnd - mStart - mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
startTime: 07:00, endTime: 16:00, breakTime 00.00
That will result with workedHours being 10.00.
This is from the chrome console:
You need to use the subtract method
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// breaking hours and minutes. needed format: HH:mm
var startHours = originalStartTime.substring(0, 2).replace(':', ''),
startMinutes = originalStartTime.substring(3, 5),
endHours = originalEndTime.substring(0, 2).replace(':', ''),
endMinutes = originalEndTime.substring(3, 5),
breakHours = originalBreakTime.substring(0, 2).replace(':', ''),
breakMinutes = originalBreakTime.substring(3, 5);
// momentJs variables
var mStart = moment().hour(startHours).minute(startMinutes),
mEnd = moment().hour(endHours).minute(endMinutes),
mBreak = moment.duration(breakHours * 60 + +breakMinutes, 'minutes');
var result = mEnd.subtract(mStart).subtract(mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
}
CalculateTime();
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="startTime" value="07:00" />
<input id="endTime" value="16:00" />
<input id="breakTime" value="00.30" />
<input id="workedHours" />
I think a more momentjs way is
function CalculateTime() {
try {
var originalStartTime = $('#startTime').val(),
originalEndTime = $('#endTime').val(),
originalBreakTime = $('#breakTime').val();
// momentJs variables
var mStart = moment(originalStartTime, 'HH:mm'),
mEnd = moment(originalEndTime, 'HH:mm'),
mBreak = moment.duration(originalBreakTime);
var result = mEnd.subtract(mStart).subtract(mBreak).format('HH:mm');
$('#workedHours').val(result + " timmar");
} catch (err) {
$('#workedHours').val(err);
}
}
CalculateTime();
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="startTime" value="07:00" />
<input id="endTime" value="16:00" />
<input id="breakTime" value="00:30" />
<input id="workedHours" />
Related
I have a textbox which allows users to choose a date from a calendar in mm/dd/yyyy format. I used the pikaday and moment libraries to achieve this. Now, if the user selects a date that is not in the future, I want to show an error in a label saying that the date is invalid. What is the 'best' way to achieve this? Working with dates in Javascript turned out to be quite a headache.I have provided my current approach:
textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
moment.diff requires a moment object. todayDate is assigned as string in this case.
Also consider quick exit when the user is still typing
Have a look at the example.
var dateInput = document.getElementById('txtDepartureDate');
var lblError = document.getElementById('lblError');
function setError(text) {
lblError.innerText = text
}
function oninputDeparture() {
var value = dateInput.value;
var dateValue = moment(value, 'DD/MM/YYYY');
if (value.length < 10 || !dateValue.isValid()) {
return;
}
var todayDate = moment();
var daysDiff = todayDate.diff(dateValue, 'days');
if (daysDiff >= 0 && !dateValue.isAfter(todayDate, 'days')) {
setError("Departure Day should be after today");
} else {
setError("");
}
}
setTimeout(() => {
dateInput.value = moment().add(1, 'days').format('DD/MM/YYYY')
oninputDeparture()
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<input id="txtDepartureDate" type="text" oninput="oninputDeparture()" />
<div id="lblError"></div>
I want new date range in each box, but it return only last text-box date range. I also made text boxes id's dynamic but still I am facing this issues. I have start date and end date for each text box and I calculated date range in PHP for start date and end date and disabled all those dates which is selected by user in their start date and date all is working fine but it returns last textbox dates disabled in datepicker.
Here is the screenshot-
Sample Image
Javascript function for datepicker to disbaled dates for each box -
$(function () {
var count = $('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
alert(dateRange);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
}
});
HTML for create boxes id's dynamic and fetch values from it.
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssStartDate[]" id="projectAssStartDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssEndDate[]" id="projectAssEndDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input id="calendarDateString<?php echo $id;?>" name="calendarDateString<?php echo $id;?>" title='D-MMM-YYYY' type="text" value="<?php echo $string;?>" />
<input id="projectsId" name="projectsId[]" type="hidden" value="<?php echo $rows['PROJECT_ID'];?>" />
<input id="usersId" name="usersId[]" type="hidden" value="<?php echo $rows['UM_ID'];?>" />
Please check the answer and reply whether this is the way you needed it to go. If not please comment what change you want with respect to this below code result. And I'm sorry that I have manipulated few of your values to ease my result. Will give details explanation if this is what you are expecting.
$(function () {
var count = 2;//$('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
// populate the array
var startDatearray= ["index 0","2016-06-15","2016-06-20"]; // you dont need to create this array .. just fetch these dates from your database as u need
var endDatearray=["index 0","2016-06-21","2016-06-25"];
var i;
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
}
});
Somehow I can't create external javascript files. If I import them from other examples, they work fine but if it is files I create and import them, they don't work. They are working fine if I inclued them into the html but if I reference them they don't work. I don't know what I am doing wrong.
Here's my html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Documento sem tÃtulo</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.ui.draggable.js" type="text/javascript"></script>
<!-- Core files -->
<script src="jquery.alerts.js" type="text/javascript"></script>
<body>
<script type="text/javascript" src="horario.js"></script>
<div id="entrada">
<input id="time" class="inputs" type="text" maxlength="2"></input>
<input id="time2" class="inputs" type="text" maxlength="2"></input>
<button class="inputs" id="confirm_button" class="inputs1" onKeyPress="localStore()" onClick="localStore()">entrada</button>
</div>
<div id="result"></div>
<div id="millsentr"></div>
<div id="millssai"></div>
<div id="mills"></div>
<div id="totHoras"></div>
</body>
</html>
And here's the javascript file:
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(".inputs1").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(document).ready( function() {
$("#confirm_button").click( function() {
jConfirm('Can you confirm this? ', 'Confirmation Dialog', function(r) {
var entradasaida = 0;
entradasaida = localStorage.getItem("entradasaida");
if(r == true){
if(entradasaida == 0){
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var mills = date.getTime();
localStorage.setItem("horas", time);
localStorage.setItem("mins", time2);
localStorage.setItem("entradasaida",1);
localStorage.setItem("millsEnt",mills);
$('#confirm_button').text("Saida");
$('#time, #time2').val("");
$('#millsentr').text(mills);
} else{
var horasEnt = localStorage.getItem("horas");
var minsEnt = localStorage.getItem("mins");
var entrada = localStorage.getItem("millsEnt");
localStorage.setItem("entradasaida",0);
$('#confirm_button').text("Entrada");
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date1 = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var millssai = date1.getTime();
$('#millssai').text(millssai);
var totMills = (millssai - entrada)
var horas = time - horasEnt;
var mins = time2 - minsEnt;
if(mins < 0){
mins = mins*(-1);
horas = horas-1;
}
var totHoras = horas+":"+mins
$('#totHoras').text(totHoras);
$('#mills').text(totMills);
$('#time, #time2').val("");
}
} else{r == false}
});
});
});
In this, the horario.js is the file I created and is not working, the other script files I used from examples are working ok.
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 9 years ago.
This script counts the days between two dates and shows the result on a span element:
<span id="result"></span>
But instead I want to show the result as value of an input element:
<input name="name" type="text" id="name" value="i want count days here " />
How can I do this?
This is the complete code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-datepicker {font-size:11px;}
</style>
<script>
$(function() {
$( "#from" ).datepicker({
onSelect: calculate
});
});
$(function() {
$( "#to" ).datepicker({
onSelect: calculate
});
});
</script>
</head>
<body>
<form class="formwhite">
<table>
<tr><td>From:</td><td><input type="text" id="from" onKeyUp="calculate();" /> </td></tr>
<tr><td>To:</td><td><input type="text" id="to" onKeyUp="calculate();" /></td></tr>
</table>
</form>
<span id="result"></span>
<script>
var calculate = function() {
var from = document.getElementById("from").value;
var fromdate = from.slice(3, 5);
fromdate = parseInt(fromdate);
var frommonth = from.slice(0, 2);
frommonth = parseInt(frommonth);
var fromyear = from.slice(6, 10);
fromyear = parseInt(fromyear);
var to = document.getElementById("to").value;
var todate = to.slice(3, 5);
todate = parseInt(todate);
var tomonth = to.slice(0, 2);
tomonth = parseInt(tomonth);
var toyear = to.slice(6, 10);
toyear = parseInt(toyear);
var oneDay = 24*60*60*1000;
var firstDate = new Date(fromyear,frommonth,fromdate);
var secondDate = new Date(toyear,tomonth,todate);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if (diffDays)
document.getElementById("result").innerHTML=diffDays;
}
</script>
</body>
</html>
So you're asking the question: "How do I get a value from one field and set it in another?" You want http://api.jquery.com/val/ :
$("#name").val($("#result").val());
$("#result").val() gets whatever value the element with id result has.
$("#name").val(value) sets the value of the element with id name
Or, simply add (or replace) the line
document.getElementById("name").value = diffDays;
in the same if block as where you have
document.getElementById("result").innerHTML = diffDays;
Here's your entire <script> block, with my one line added:
<script>
var calculate = function() {
var from = document.getElementById("from").value;
var fromdate = from.slice(3, 5);
fromdate = parseInt(fromdate);
var frommonth = from.slice(0, 2);
frommonth = parseInt(frommonth);
var fromyear = from.slice(6, 10);
fromyear = parseInt(fromyear);
var to = document.getElementById("to").value;
var todate = to.slice(3, 5);
todate = parseInt(todate);
var tomonth = to.slice(0, 2);
tomonth = parseInt(tomonth);
var toyear = to.slice(6, 10);
toyear = parseInt(toyear);
var oneDay = 24*60*60*1000;
var firstDate = new Date(fromyear,frommonth,fromdate);
var secondDate = new Date(toyear,tomonth,todate);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if (diffDays) /* THE NEW STUFF IS RIGHT HERE*/ {
document.getElementById("result").innerHTML=diffDays;
document.getElementById("name").value=diffDays;
} // THE NEW STUFF ENDS HERE
}
</script>
I'm using a datepicker to choose dates, I want to calculate difference between dates choosen & then alert the difference.I'm not able see the code work
HTML datepicker
<input type="date" size="8" name="advDurFrom" />
<input type="date" size="8" name="advDurTo"/>
Javascript
$('input[name=advDurFrom]').click(function() {
var x=$('input[name=advDurFrom]').val();
var date1 = new Date(x);
});
$('input[name=advDurTo]').click(function() {
var y=$('input[name=advDurTo]').val();
var date2 = new Date(y);
});
$('input[name=advDurTo]').focusout(function() {
var diffDays = date2.getTime() - date1.getTime();
alert(diffDays);
});
Html:
<input type="date" name="startdate">
<input type="date" name="enddate">
<button id="calculate">Calculate</button>
<h2 id="result"></h2>
Script:
var startdateInput = document.querySelector('input[name="startdate"]'),
enddateInput = document.querySelector('input[name="enddate"]'),
calculateButton = document.getElementById('calculate'),
resultElement = document.getElementById('result');
calculateButton.addEventListener('click', function(e) {
if( startdateInput.value && enddateInput.value ) {
result.textContent = new Date(enddateInput.value) - new Date(startdateInput.value);
}
});
Or see the JSFiddle http://jsfiddle.net/zJTfM/
The result is the number of milliseconds between the start and end date.
$('input[name=advDurFrom]').live('change', function(e) {
var x=$(this).datepicker( "getDate" );
date1 = x.getTime();
});
$('input[name=advDurTo]').live('change', function(e) {
var y=$(this).datepicker( "getDate" );
date2 = y.getTime();
});
$('input[name=advDurTo]').live('blur', function(e) {
if(date2 && date1){
var diffDays = date2 - date1 ;
alert(diffDays);
} else {
alert("date is not selected.")
}
});
In my project I use this function to calculate difference day between 2 date,I modify some for you. see demo in jsfiddle
HTML:
<input type="text" size="8" name="advDurFrom" />
<input type="text" size="8" name="advDurTo"/>
difference days: <span class="diff"><span>
JS:
function CalendarDays(startDate, endDate) {
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.round(diff / millisecondsPerDay);
return days;
}
function common_getDateFromUI(str) {
var arr = str.split("/");
var returnDate = new Date(arr[2], arr[1] - 1, arr[0], 0, 0, 0, 0);
return returnDate;
}
$().ready(function(){
$('input[name="advDurFrom"],input[name="advDurTo"]').datepicker( {
showOn : "both",
dateFormat : "dd/mm/yy",
changeMonth : true,
changeYear : true,
buttonImageOnly : true,
onSelect : function(dateText, inst) {
var day1 = common_getDateFromUI($('input[name="advDurFrom"]').val());
var day2 = common_getDateFromUI($('input[name="advDurTo"]').val());
$(".diff").html(CalendarDays(day1,day2));
}
});
});
I think you need to declare the variable globally. Try this code. This is working perfectly for me.
var date1 = "";
var date2 = "";
$('#advDurFrom').click(function () {
var x = $(this).val();
date1 = new Date(x);
});
$('#advDurTo').click(function () {
var y = $(this).val();
date2 = new Date(y);
});
$('#advDurTo').focusout(function () {
var diffDays = date2.getTime() - date1.getTime();
alert(diffDays);
});
And Change the HTML to
<input type="date" size="8" id="advDurFrom" />
<input type="date" size="8" id="advDurTo" />
getTime returns millisecond, you just need to convert into the correct unit. Here an example with days difference. Also use blur event not click or you will end up assigning the value before the user actually inputs it
var isOK = false;
var isOK2 = false;
$('input[name=advDurFrom]').blur(function () {
var x = $('input[name=advDurFrom]').val();
try {
date1 = new Date(x);
isOK = !isNaN(date1);
} catch (e) {
isOK = false;
}
printDiff();
});
$('input[name=advDurTo]').blur(function () {
var y = $('input[name=advDurTo]').val();
try {
date2 = new Date(y);
isOK2 = !isNaN(date2);
} catch (e) {
isOK2 = false;
}
printDiff();
});
function printDiff(){
if (isOK && isOK2) {
var one_day = 1000 * 60 * 60 * 24;
var diff = Math.ceil((date2.getTime() - date1.getTime()) / (one_day));
console.log(diff + ' days');
}
}
Fiddle here