JavaScript Time picker insert from real time - javascript

In a row I have a clock, which shows the time when I log in. How I can make it real, so its ticking all the time and shows real time? Please see picture ( row with 20.03.21 22:25 )
cms with time
<input type="text" class="light1" name="Date" value="[[:Date:]]" /><br/>
<input type="text" class="light1" id="txt" name="Now" readonly="readonly" value="[:NOW:]" />
<span style="position:relative; top:0px; left:0px;">↑</span>

If you want a text input to update every second with the time, you could implement something like this:
<input type="text" id="myTime" />
<script>
window.onload = function () {
setInterval(function () {
var newDate = new Date();
document.getElementById('myTime').value = newDate.toLocaleString();
}, 1000);
}
</script>

Code taken from Clock and date javascript
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date(new Date().getTime() + diff);
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yyyy = currentTime.getFullYear();
/* let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12; */
hours = pad(hours);
timeOutput.value = "" +
yyyy + "/" + month + "/" + day +
" " +
hours + ":" +
minutes + ":" +
seconds// + dn;
}
let timeOutput;
let serverTime;
let diff;
window.addEventListener("load", function() {
timeOutput = document.getElementById("timedate");
serverTime = new Date("2020/03/21 22:23:24");// change to new Date("[[:Date:]]"); for example
diff = new Date().getTime() - serverTime.getTime();
setInterval(timedate, 1000);
});
<input type="text" id="timedate" class="light1" name="Date" value="" /><br/>

Related

React "Rendered fewer hooks than expected." when switching from Desktop to Mobile component everytime a useEffect hook is called in "homeSection"

NOTE: I don't use media queries for switching from desktop to mobile , i have 2 different
components that get rendered depending on state of screenwidth if that has anything to do
with it
This is my homesection component that displays my age
If i change the timer to 10000 the application crashes after 10 seconds instead.
function HomeSection() {
const timer = 1000;
const [myAge, setAge] = useState();
//this useEffect hook gets called every second to update my age on the page if i remove
//this hook the switch from desktop to mobile works without giving any errors. but when
//i have this in i get "Rendered fewer hooks than expected" when i have switched from desktop to mobile and this hook is called
useEffect(() => {
const interval = setInterval(() => {
setAge(getAge("2000/01/01"));
console.log(" hello world");
}, timer);
return () => clearInterval(interval);
}, []);
....
//function to calculate age
function getAge(date) {
let months = " month ";
let days = " day ";
let hours = " hour ";
let minutes = " minute ";
let seconds = " second ";
var today = new Date();
var birthDate = new Date(date);
var YearDiff = today.getYear() - birthDate.getYear();
var monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff > 1) {
months = " months ";
}
var myDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
var testing = myDay + today.getDate();
var daysDiff = testing - birthDate.getDate();
if (daysDiff > 1) {
days = " days ";
}
var hoursDiff = today.getHours() - birthDate.getHours();
if (hoursDiff > 1) {
hours = " hours ";
}
var minDiff = today.getMinutes() - birthDate.getMinutes();
if (minDiff > 1) {
minutes = " minutes ";
}
var secDiff = today.getSeconds() - birthDate.getSeconds();
if (secDiff > 1) {
seconds = " seconds ";
}
var Age =
YearDiff +
" years " +
monthDiff +
months +
daysDiff +
days +
hoursDiff +
hours +
minDiff +
minutes +
secDiff +
seconds;
return Age;
}
return (
<div className="Section" id="homePage">
<h1 className="helloworld">Hello World</h1>
<h2> i am {myAge}</h2>
</div>
);
}

Print Time Slot In JavaScript

The problem is that when I'm taking the current time using localdate(this is my start time) variable and I'm also taking end time so I print the time between this values with 15 min of increasing time.
Example: current time is 13:04 so the further time slots will be 13:19, 13:34 and so on till end time.
function ShowLocalDate() {
var time1 = new Date();
var time2 = new Date();
var dNow = new Date();
var localdate = dNow.getHours() + ':' + dNow.getMinutes();
//meeting length
var meetingLength = parseInt('15');
//start time
var startTime = localdate
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
//end time
var endTime = '11:00 PM';
var endHour = endTime.split(':')[0];
var endMin = endTime.split(':')[1].replace(/AM|PM/gi, '');
//Check if start time is PM and adjust hours to military
if (startTime.indexOf('PM') > -1) {
if (startHour != 12) {
startHour = parseInt(startHour) + 12;
} else {
startHour = parseInt(startHour);
}
console.log(startHour);
}
//Check if end time is PM and adjust hours to military
if (endTime.indexOf('PM') > -1) {
endHour = parseInt(endHour) + 12;
console.log(endHour);
}
//Date API start time
time1.setHours(parseInt(startHour));
time1.setMinutes(parseInt(startMin));
//Date API end time
time2.setHours(parseInt(endHour));
time2.setMinutes(parseInt(endMin));
//Adding meeting length to start time, this value will be use for end time
time1.setMinutes(time1.getMinutes() + meetingLength);
while (time1 < time2) {
$('#etime').append('<option value="' + time1 + '">' + time1 + '</option>');
time1.setMinutes(time1.getMinutes() + meetingLength);
}
}
ShowLocalDate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select name="etime" id="etime">
<option value="">--Select end time--</option>
</select>
</td>
</tr>
</tr>
JSFiddle: https://jsfiddle.net/6n458ze9/18/
But I want that, suppose the start time means current time is 13:04 so the next time will be 13:20 not 13:19 and one more time is 13:35 not 13:34, till ending time.
End time will be 11:00 PM(this is fixed).
Thank you in advance.
If you want to round up time to 05, 10, 15 etc minutes you can easily add few more minutes to original time until you get minutes mod by 5 equals zero, something like this
//Adding meeting length to start time, this value will be use for end time
var endTime = time2.getMinutes() + meetingLength;
while (endTime % 5 != 0)
endTime++
time1.setMinutes(endTime);
You can just round off the start time in your code.
in below solution i am doing the same.
hope this helps
function getRoundOffDate() {
var now = new Date();
var minutes = now.getMinutes();
minutes += 5 - minutes % 5;
if (minutes == 60) {
now.setHours(now.getHours() + 1);
now.setMinutes(0);
} else {
now.setMinutes(minutes);
}
return now;
}
function ShowLocalDate() {
var time1 = new Date();
var time2 = new Date();
var dNow = getRoundOffDate();
var localdate = dNow.getHours() + ':' + dNow.getMinutes();
//meeting length
var meetingLength = parseInt('15');
//start time
var startTime = localdate
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
//end time
var endTime = '11:00 PM';
var endHour = endTime.split(':')[0];
var endMin = endTime.split(':')[1].replace(/AM|PM/gi, '');
//Check if start time is PM and adjust hours to military
if (startTime.indexOf('PM') > -1) {
if (startHour != 12) {
startHour = parseInt(startHour) + 12;
} else {
startHour = parseInt(startHour);
}
console.log(startHour);
}
//Check if end time is PM and adjust hours to military
if (endTime.indexOf('PM') > -1) {
endHour = parseInt(endHour) + 12;
console.log(endHour);
}
//Date API start time
time1.setHours(parseInt(startHour));
time1.setMinutes(parseInt(startMin));
//Date API end time
time2.setHours(parseInt(endHour));
time2.setMinutes(parseInt(endMin));
//Adding meeting length to start time, this value will be use for end time
time1.setMinutes(time1.getMinutes() + meetingLength);
while (time1 < time2) {
$('#etime').append('<option value="' + time1 + '">' + time1 + '</option>');
time1.setMinutes(time1.getMinutes() + meetingLength);
}
}
ShowLocalDate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select name="etime" id="etime">
<option value="">--Select end time--</option>
</select>
</td>
</tr>
</tr>
If end time is fixed to 11:00PM, then you can start from backwards
function ShowLocalDate() {
var time1 = new Date();
var time2 = new Date();
var dNow = new Date();
var localdate = dNow.getHours() + ':' + dNow.getMinutes();
//meeting length
var meetingLength = parseInt('15');
//start time
var startTime = localdate
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
//end time
var endTime = '11:00 PM';
var endHour = endTime.split(':')[0];
var endMin = endTime.split(':')[1].replace(/AM|PM/gi, '');
//Check if start time is PM and adjust hours to military
if (startTime.indexOf('PM') > -1) {
if (startHour != 12) {
startHour = parseInt(startHour) + 12;
} else {
startHour = parseInt(startHour);
}
console.log(startHour);
}
//Check if end time is PM and adjust hours to military
if (endTime.indexOf('PM') > -1) {
endHour = parseInt(endHour) + 12;
console.log(endHour);
}
//Date API start time
time1.setHours(parseInt(startHour));
time1.setMinutes(parseInt(startMin));
//Date API end time
time2.setHours(parseInt(endHour));
time2.setMinutes(parseInt(endMin));
time2.setSeconds(0);
//Adding meeting length to start time, this value will be use for end time
time1.setMinutes(time1.getMinutes() + meetingLength);
while (time1 < time2) {
$('#etime option:first').after('<option value="' + ('00' + time2.getHours()).slice(-2) + ':' + ('00' + time2.getMinutes()).slice(-2) + '">' + ('00' + time2.getHours()).slice(-2) + ':' + ('00' + time2.getMinutes()).slice(-2) + '</option>');
time2.setMinutes(time2.getMinutes() - meetingLength);
}
$('#etime option:first').after('<option value="' + ('00' + time1.getHours()).slice(-2) + ':' + ('00' + time1.getMinutes()).slice(-2) + '">' + ('00' + time1.getHours()).slice(-2) + ':' + ('00' + time1.getMinutes()).slice(-2) + '</option>');
}
ShowLocalDate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<select name="etime" id="etime">
<option value="">--Select end time--</option>
</select>
</td>
</tr>
</tr>

How to reset drop down if value change?

I'm working on my project where I have three drop down boxes. User can pick Start time, Meeting Length and End time. My function works fine but I'm missing one more thing, so If user select all of three drop downs they will get all end times in last drop down but now I want if they change meeting length or start time, my end time drop box should give them values with the valid records. Current code works fine if they select everything once but if they change start time or meeting length my end time is still the same.
Here is my jsfiddle with the working example:
https://jsfiddle.net/dmilos89/vy0yy7h9/4/
I tried to reset my function with something like this:
$('#meet_leng').on('chnage');
inside of my existing function but that did not help. If anyone knows how I can refresh my function each time after I change values in my start time and meeting length drop downs please let me know.
$(function() {
//This loop populate values fro meeting length dropdown
for (var i = 5; i <= 60; i += 5) {
$('#meet_leng').append('<option value="' + i + '">' + i + ' min' + '</option>')
}
//Populate start time dropdown with values
for (var i = 700; i <= 1700; i += 15) {
var mins = i % 100;
var hours = parseInt(i / 100);
if (mins > 45) {
mins = 0;
hours += 1;
i = hours * 100;
}
var AmPm = " AM";
//set hours 12 to PM
if (hours == 12) {
AmPm = " PM";
}
//format all hours greater than to PM
if (hours > 12) {
hours = hours - 12;
AmPm = " PM";
}
//populate stime with values
$('#stime').append('<option value="' + ('0' + (hours)).slice(-2) + ':' + ('0' + mins).slice(-2) + AmPm + '">' + ('0' + (hours)).slice(-2) + ':' + ('0' + mins).slice(-2) + AmPm + ' </option>')
}
//onChange function set end time based on start time and meeting length
$('#meet_leng').on('change', function() {
if ($('#stime').val() == '0') {
alert('You have to pick start time first.')
} else {
if ($('#meet_leng').val() == '0') {
$('#hideSlots').hide();
} else {
//convert variables for start and end time to new Date
var time1 = new Date();
var time2 = new Date();
//meeting length converts to int
var meetingLength = parseInt($('#meet_leng').val());
//start time split into hours and minutes
var startTime = $('#stime').val();
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
//end time split into hours and minutes
var endTime = '05:00 PM';
var endHour = endTime.split(':')[0];
var endMin = endTime.split(':')[1].replace(/AM|PM/gi, '');
//Check if start time is PM and adjust hours to military
if (startTime.indexOf('PM') > -1) {
if (startHour != 12) {
startHour = parseInt(startHour) + 12;
} else {
startHour = parseInt(startHour);
}
}
//Check if end time is PM and adjust hours to military
if (endTime.indexOf('PM') > -1) {
endHour = parseInt(endHour) + 12;
}
//Date API start time set hours and minutes
time1.setHours(parseInt(startHour));
time1.setMinutes(parseInt(startMin));
//Date API end time set hours and minutes
time2.setHours(parseInt(endHour));
time2.setMinutes(parseInt(endMin));
//Adding meeting length to start time
time1.setMinutes(time1.getMinutes() + meetingLength);
//while loop checks for time values and increment end time for meeting interval
while (time1 <= time2) {
var amPm = " AM";
var hourEnd = time1.getHours();
var minEnd = time1.getMinutes();
if (hourEnd >= 12) {
hourEnd = (hourEnd == 12) ? hourEnd : hourEnd - 12;
amPm = " PM";
}
if (hourEnd == 24) {
hourEnd = 12;
}
minEnd = ('' + minEnd).length > 1 ? minEnd : '0' + minEnd;
$('#etime').append('<option value="' + hourEnd + ':' + minEnd + ' ' + amPm + '">' + hourEnd + ':' + minEnd + ' ' + amPm + '</option>');
time1.setMinutes(time1.getMinutes() + meetingLength);
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<th>Start Time:</th>
<td>
<select name="stime" id="stime">
<option value="0">--Select start time--</option>
</select>
</td>
</tr>
<br/>
<tr>
<th>Metting Length:</th>
<td>
<select name="meet_leng" id="meet_leng">
<option value="0">--Select length--</option>
</select>
</td>
</tr>
<br/>
<tr>
<th>End Time:</th>
<td>
<select name="etime" id="etime" />
<option value="0">--Select end time--</option>
</select>
</td>
</tr>
You want to either set the value:
$('#etime').val("new value");
or select the index:
$('#etime').get(0).selectedIndex = 1;
remember that indexes start at 0.
you would do this after the while loop that populates all the end time options.
Please try below code
$('#meet_leng').on('chnage',function(){
$('#etime').val("FirstIndexValue")
});
//FirstIndexValue= #etime default value

displaying current date in a text box - javascript

I am having great difficulty getting the current date to be inputted into a text box within a form i am creating as a default value. at the moment i have the following code, which i believe creates the current date, followed by the text box code which i am unsure on how to modify in order for the date to be displayed inside.
function getDate(){
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
document.getElementById("frmDate").value = datestring();
}
<input type="text" name="frmDateReg" required id="frmDate" value="getDate()">
if anyone could suggest how to create todays date and input it into the textbox as default it would be greatly appreciated. (Please excuse any format issues as i am new to stack overflow) Thanks
You've got the right idea. It's just out of order:
<input type="text" name="frmDateReg" required id="frmDate" value="">
function getDate(){
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
document.getElementById("frmDate").value = datestring;
}
getDate();
Your code is correct, except that adding the function call in the value doesn't do anything. You need something else to trigger the function. The way I have it there, it will execute automatically when the page loads.
Aslo, datestring is not a function. It's just a variable. So you can leave off the ()
Try this Jquery code, this will work
$(document).ready(function () {
var dateNewFormat, onlyDate, today = new Date();
dateNewFormat = today.getFullYear() + '-';
if (today.getMonth().length == 2) {
dateNewFormat += (today.getMonth() + 1);
}
else {
dateNewFormat += '0' + (today.getMonth() + 1);
}
onlyDate = today.getDate();
if (onlyDate.toString().length == 2) {
dateNewFormat += "-" + onlyDate;
}
else {
dateNewFormat += '-0' + onlyDate;
}
$('#mydate').val(dateNewFormat);
});
razor view for this
#Html.TextBoxFor(m => m.StartedDate, new { #id = "mydate", #type = "date", #class = "form-control" })
This simple solution worked out for me. You can show the current date using window.onload function of javascript. See the output.
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
window.onload = function(){
document.getElementById("date").value = datestring;
}
<input type="text" id="date"/ >
<html>
<body onload="myFunction()">
Date: <input type="text" id="demo"/>
<script>
function myFunction() {
document.getElementById('demo').value= Date();
}
</script>
</body>
</html>
Use this code. this will helpful
<input type="text" name="frmDateReg" required id="frmDate" >
<script>
function getDate(){
var todaydate = new Date();
var day = todaydate.getDate();
var month = todaydate.getMonth() + 1;
var year = todaydate.getFullYear();
var datestring = day + "/" + month + "/" + year;
document.getElementById("frmDate").value = datestring; //don't need ()
}
document.getElementById("frmDate").onload = getDate();
</script>
html
<input type="text" id="frmDate"></input>
JavaScript
var date = new Date();
document.getElementById("frmDate").value = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
Jsfiddle Demo
<script TYPE="text/javascript" LANGUAGE=JAVASCRIPT>
var currentDate = new Date();
var date1 = currentDate.getMonth()+1;
var mon = currentDate.getDate();
if (mon<10)
mon="0"+mon
var year = currentDate.getYear();
var hour = currentDate.getHours();
var dn="pm"
if (hour<12)
dn="am"
if (hour>12)
hour=hour-12
if (hour==0)
hour=12
var minute = currentDate.getMinutes();
if (minute < 10){
minute = "0" + minute
}
var second = currentDate.getSeconds();
if (second < 10){
second = "0" + second
}
var today = date1+"/"+mon+"/"+year+" Time: "+hour+":"+minute+":"+second+" "+dn
var filePath = "\\\\servername\\maindirectory\\somedirectory\\filenametopostto.xlsx";
function setDate()
{
f1.tDate.value=today;
}
</script>
Result in your text box is:
5/28/2019 Time: 3:03:01 pm
If you want to show the current date on the input field date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
// today = yyyy + '/' + mm + '/' + dd;
today = `${yyyy}-${mm}-${dd}`;
document.getElementById('dateto1').value = today;
<div class="col-lg-4">
<label>Date</label>
<input type="date" name="dateto1" id="dateto1" class="form-control">
</div>

get javascript to write to variable rather than document.write

I have the following javascript that prints the timestamp:
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>
However I want to use this timestamp in many places in the page, how can i call it like $timestamp so i can control where its placed?
Thanks in advance.
Set a variable, like:
var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;
and later in code use that variable to show info in your page, like:
var container = document.getElementById('container1');
container.innerHTML = timestamp;
where 'container1' is a html element like span, div, p, etc. ex:
<span id="container1"></span>
answer
<script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<span id="txt"></span>
<script type="text/javascript">
startTime().swap('txt');
</script>

Categories