jquery - assigning values to an input not working - javascript

I have three input controls in a form as,
date (which display the current date but user can select any date from a calendar)
start time(current time)
end time(start time + 30 minutes)
on page load
HTML:
Date:<input type="text" name="txtdate" id="txtdate" />
Start time:<input type="time" name="txtstart" id="txtstart" />
End time:<input type="time" name="txtend" id="txtend" />
I use jquery to get this done and the code is as follows
jquery:
$(document).ready(function() {
$("#txtdate").datepick({dateFormat:'yyyy-mm-dd',minDate: 0});
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var year1 = d.getFullYear();
var hour = d.getHours();
var mins = d.getMinutes();
var today = year1 + '/' + month + '/' + day;
$("#txtdate").val(today);
var time = hour + ":" + mins;
$("#txtstart").val(time);
var a = time.split(':');
var totmins = (+a[0])* 60 + (+a[1])+30;
var nhour = Math.floor(totmins/60);
var nmins = totmins%60;
var ntime = nhour + ":" + nmins;
$("#txtend").val(ntime);
});
in the above code it displays the current date, time and adds up 30 minutes to the current time correctly but sometimes when assigning values, the start time and end time fields don't display the time! for an example,
when current time is 12.00 AM, no value is displayed in start time and end time input fields
I don't see any error in the code but since i'm new to jquery i need to know if i had done anything wrong here (may be when assigning values) or is there another way to do this?
Note:
It should be noted that I have use HTML 5 input type time control to input start time and end time

My guess to your question is that after adding 30 minute to your Start Time, End Time is already the next day.
Take this for example.
Start Time: 23.50
Based on your calculation, +30min gives you
End Time: 24.20
24.20 is an invalid value for input[type='time']
Edit: Jacob's answer solves the problem to your flawed algorithm.
Edit 2: Modifying Jacob's answer, this will get you the endDate
var d = new Date(); //get current time.
var thirtyMinutes = 30*60*1000; //30 minutes in milliseconds
var futureDate = new Date(d.getTime() + thirtyMinutes); //current time in milliseconds + 30 minutes in milliseconds.
var endDateHour = futureDate.getHours();
var endDateMinutes = futureDate.getMinutes();
if (endDateMinutes<10) {
endDateMinutes = "0"+endDateMinutes;
}
var endDate = endDateHour + ':' + endDateMinutes;

Don't bother with this complicated "add 30 minutes" logic when you can simply use Date which is already good at date/time math.
var d = new Date();
// ...
var thirtyMinutes = 30*60*1000;
var futureDate = new Date(d.getTime() + thirtyMinutes);
var ntime = futureDate.getHours() + ':' + futureDate.getMinutes();

Related

Date and Time Difference and Average time

I have two times (basically start time and end time). Also, I have the number of questions played by the user. I wanna know the average time user spent for each question.
//startGameTime: 2019-07-27T07:58:42.000Z
//endGameTime: 2019-07-27T07:59:57.000Z
function averageQuestionTime(startGameTime, endGameTime, totalNumberOfQuestions) {
var d1 = new Date(startGameTime);
var d2 = new Date(endGameTime);
var d1msecs = new Date(d1).getTime(); // get milliseconds
var d2msecs = new Date(d2).getTime(); // get milliseconds
var avgTime = (d1msecs + d2msecs) / totalNumberOfQuestions;
var date = new Date(avgTime);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
return (day + ":" + hour + ":" + min + ":" + sec)
}
I understand my logic is completely flawed as the units for date and time and nos of questions are different. What is the best way to achieve the result ?
There are good libraries which prevent the users from having to reinvent the wheel every time they want to manipulate date/time in Node.
Obtaining time difference is pretty simple (I can see you are doing it correctly to obtain the difference in milliseconds) and libraries make them even simpler.
See how simple it is using momentJS
var moment = require('moment');
var startDate = moment('2019-7-24 00:00:00', 'YYYY-M-DD HH:mm:ss');
var endDate = moment('2019-7-24 05:27:31', 'YYYY-M-DD HH:mm:ss');
var diffSeconds = endDate.diff(startDate, 'seconds');
var diffHours endDate.diff(startDate, 'seconds');
console.log(`Avg in secs: ${diffSeconds / totalNumberOfQuestions}`);
console.log(`Avg in secs: ${diffHours/ totalNumberOfQuestions}`);

Why it happens? Strange behavior w/ JavaScript with Date() subtraction. CodePen + Video

I am new with JavaScript and I am building a simple app to calculate my worked hours at work.
When I am subtracting two dates - it works fine (the result is 1:30, for example), but as soon as I add the third date it has a strange behavior and the result is +1 added hour and minutes are 59 44 29 14 (always -1 minute , while the third date itself is always a 0,15,30,45 minutes). I assume the +1 added hour is -1,but it was converted to an absolute number by Date().
Video link to the problem :
https://youtu.be/EyhaVgwxOpw
CodePen : https://codepen.io/anon/pen/PLNqMa
Code
var startHr,
startMin,
endHr,
endMin,
pause;
$(".start,.end,.pochivka").change(function () {
startHr = Number($('#starthr').children("option:selected").val());
startMin = Number($('#startmin').children("option:selected").val());
endHr = Number($('#endhr').children("option:selected").val());
endMin = Number($('#endmin').children("option:selected").val());
pause = Number($('#pause').children("option:selected").val());
});
$(".calculate").click(function(){
// Refer to starting hours and ending hours which get their value from chosen fields
var secondTime = startHr + ":" + startMin +":00";
var firstTime = endHr + ":" + endMin + ":00";
// breakTime also gets from the same place, but has strange behaviour
var breakTime = "00:" + pause + ":00";
console.log(breakTime);
let startHour = new Date().setHours(...(firstTime.split(":")));
let endHour = new Date().setHours(...(secondTime.split(":")));
let removeBreakHours = new Date().setHours(...(breakTime.split(":")));
// Disable next line (and enable the code with next comments)
// to see how normal it works without the bug
// Maybe it happens because I have 2 subtractions?
let finalHours = new Date(startHour - endHour - removeBreakHours);
// Now enable next line.It is the code without "Break times remove"
// let finalHours = new Date(startHour - endHour);
// ------------
var workedHours = finalHours.getUTCHours() +":"+ finalHours.getUTCMinutes();
$('.workHours').text(workedHours);
})
I've made it working by adding the breaktime as negative minutes
$(".calculate").click(function(){
// Refer to starting hours and ending hours which get their value from chosen fields
var secondTime = startHr + ":" + startMin +":00";
var firstTime = endHr + ":" + endMin + ":00";
let startHour = new Date().setUTCHours(...(firstTime.split(":")));
let endHour = new Date().setUTCHours(...(secondTime.split(":")));
let finalHours = new Date(startHour - endHour);
finalHours.setMinutes(- +pause);
// ------------
var workedHours = finalHours.getUTCHours() +":"+ finalHours.getUTCMinutes();
$('.workHours').text(workedHours);
})
In your example you were subtracting milisseconds (to be precise miliseconds passed since 1st of Jan 1970 UTC), so I guess when JS rounds the results is rounding to lower value, resulting in 1 less minute than expected. But I haven't proved it.

Get difference in months and list the months in an array between two dates in javascript

I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

How To Make A Default Text Display For This Script?

I'm using a script to display the current date to someone, but I want to do two things to it.
First, I want to change the format to MM/DD/YY, so it's only showing the year in 2 digits.
Then second, how can I add a default? So if it's not able to be pulled by someone, it will show "Today" instead of a date?
Here's the script if anyone could help:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
Working FIDDLE Demo
Add a div to your HTML and put your default text inside it:
<div id="date">Today</div>
Then with javascript, change it, and if the user don't have javascript, it remains not changed:
// create date
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + "/" + day + "/" + (year + '').substring(2);
// now insert it
document.getElementById('date').innerHTML = date;
[!] Don't forget to add the JS after your element or add it to document ready.
I don't see any reason for this to fail, If javascript is enabled in the client it should work, still if you want error handling
try {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + (year + '').substring(2))
}catch(e){
document.write('Today');
}
You can get the last two digits of day by doing String(year).substring(2,4). So you end up with:
console.log(day+"/"+month+"/"+String(year).substring(2,4));
To set defaults you can use the following:
var demo = value1 || default
You can play around with these ideas here

Categories