Can't get the current date to display in the textbox - javascript

<!DOCTYPE>
<html>
<head>
<script>
function displayDate() {
var date = new Date();
const monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var Date = date.getDate();
var month = monthArray[date.getMonth()];
var year = date.getFullYear();
var day = dayArray[date.getDay()];
var hours = date.getHours() % 12;
var minutes = date.getMinutes();
var amPm = "AM";
if (hours < 10) {
hours = "0" + hours;
}
if (date.getHours() > 12) {
amPm = "PM";
}
var str = Date + " " + month + " " + year + " " + day + " " + hours + ":" + minutes + " " + amPm;
document.getElementById("date1").value = str;
}
</script>
</head>
<body>
Current date: <input id="date1" type="text" size="30" onload="displayDate()">
</body>
</html>
Hi guys, I am trying to display the current date in the textbox. However, I can't seem to get it to work. When the program ran, the textbox did not display anything. I tried using a console.log function to print the output in the console but it didn't seem to work as well. Kindly advise for a solution, thank you.

You can remove the onload() and simply call your function when the window loads.
Something like that:
document.addEventListener("DOMContentLoaded", function() {
displayDate();
});
However, your code has a problem you should be aware of. You cannot name a variable with the name "Date" because this causes conflict with Global function Date(). Instead, rename your variable somehow else. I will include my code to show you what I mean.
<!DOCTYPE>
<html>
<head>
</head>
<body>
Current date: <input id="date1" type="text" size="30">
</body>
<script>
function displayDate() {
console.log("hey!");
let date = new Date();
const monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayArray = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var theDate = date.getDate();
var month = monthArray[date.getMonth()];
var year = date.getFullYear();
var day = dayArray[date.getDay()];
var hours = date.getHours() % 12;
var minutes = date.getMinutes();
var amPm = "AM";
if (hours < 10) {
hours = "0" + hours;
}
if (date.getHours() > 12) {
amPm = "PM";
}
var str = theDate + " " + month + " " + year + " " + day + " " + hours + ":" + minutes + " " + amPm;
document.getElementById("date1").value = str;
}
document.addEventListener("DOMContentLoaded", function() {
displayDate();
});
</script>
</html>

Related

How to retain my date textbox value when reset

I have a textbox that gets the current date and time. I have tried calling the function to get the date but it is not working.
function getDate() {
var td = new Date();
var date = td.getDate();
var month = td.getMonth();
var mon = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var m = mon[month];
var year = td.getFullYear();
var day = td.getDay();
var da = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var d = da[day];
var hour = td.getHours();
var min = td.getMinutes();
var datestring = date + " " + m + " " + year + " " + d + " " + hour + ":" + (min <10?'0':'') + min;
document.getElementById("date").value = datestring;
}
getDate();
<form id="myForm">
<label for="date">Current date: </label><br>
<input type="text" id="date" readonly size="30" onreset="getDate()"><br>
<input type="reset">
</form>
You have to move the getDate function to button not input.
Solution
function getDate() {
var td = new Date();
var date = td.getDate();
var month = td.getMonth();
var mon = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var m = mon[month];
var year = td.getFullYear();
var day = td.getDay();
var da = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var d = da[day];
var hour = td.getHours();
var min = td.getMinutes();
var datestring = date + " " + m + " " + year + " " + d + " " + hour + ":" + (min <10?'0':'') + min;
document.getElementById("date").value = datestring;
console.log(datestring)
}
getDate();
<form id="myForm">
<label for="date">Current date: </label><br>
<input type="text" id="date" readonly size="30" /><br>
<input type="button" onClick="getDate()" value="get date">
</form>
The function called on the reset event is called before the form gets cleared, so the datestring is set when the function is called but then the form input gets cleared. You will have to do 2 things to make this work
Move onreset event to the form element
Add a set timeout so that the input element value is set after the form is reset
function getDate() {
var td = new Date();
var date = td.getDate();
var month = td.getMonth();
var mon = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var m = mon[month];
var year = td.getFullYear();
var day = td.getDay();
var da = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
var d = da[day];
var hour = td.getHours();
var min = td.getMinutes();
var datestring = date + " " + m + " " + year + " " + d + " " + hour + ":" + (min <10?'0':'') + min;
setTimeout(() => document.getElementById("date").value = datestring)
}
getDate();
<form id="myForm" onreset="getDate()">
<label for="date">Current date: </label>
<input type="text" id="date" readonly size="30" >
<input type="reset">
</form>
When a form is reset, elements adopt their defaultValue. Setting the value property does not affect the defaultValue, however setting the value attribute does.
So either set the element's value and defaultValue, or just set the value attribute instead, e.g.
function getDate() {
let {year, month, day, weekday, hour, minute} =
new Intl.DateTimeFormat('en', {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
hour: 'numeric',
minute: '2-digit',
hour12: false
}).formatToParts(new Date()).reduce(
(acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null)
);
let datestring = `${day} ${month} ${year} ` +
`${weekday} ${hour}:${minute}`;
// Do this
document.getElementById("date").setAttribute('value', datestring);
// Or this
// document.getElementById("date").value = datestring;
// document.getElementById("date").defaultValue = datestring;
}
window.onload = getDate;
<form id="myForm">
<input placeholder="Enter something to show form is reset"><br>
<label for="date">Current date: </label><br>
<input type="text" id="date" readonly size="30"><br>
<input type="reset">
</form>
I refactored the date formatting function a little too. :-)

how to change 24 hours format to 12 hours?

my question is about i am using below code for date and time in 24 hours format, but here i need to change the format to 12 hours.
please help me solve the issue.
$(document).ready(function() {
// Making 2 variable month and day
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
// make single object
var newDate = new Date();
// make current time
newDate.setDate(newDate.getDate());
// setting date and time
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
setInterval(function() {
// Create a newDate() object and extract the seconds of the current time on the visitor's
var seconds = new Date().getSeconds();
// Add a leading zero to seconds value
$("#sec").html((seconds < 10 ? "0" : "") + seconds);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$("#min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours();
// Add a leading zero to the hours value
$("#hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<div class="clock">
<div id="Date"></div>
<ul>
<li id="hours"></li>
<li id="point">:</li>
<li id="min"></li>
<li id="point">:</li>
<li id="sec"></li>
</ul>
</div>
use ("0"+hours%12).slice(-2) to do two digits 12 hours format and use (hours/12 == 0) to get AM/PM:
$(document).ready(function() {
// Making 2 variable month and day
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
// make single object
var newDate = new Date();
// make current time
newDate.setDate(newDate.getDate());
// setting date and time
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
setInterval(function() {
// Create a newDate() object and extract the seconds of the current time on the visitor's
var seconds = new Date().getSeconds();
// Add a leading zero to seconds value
$("#sec").html((seconds < 10 ? "0" : "") + seconds);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$("#min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours();
// Add a leading zero to the hours value
$("#hours").html(("0"+hours%12).slice(-2) + " " + ((hours/12 == 0)?"AM":"PM"));
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<div class="clock">
<div id="Date"></div>
<ul>
<li id="hours"></li>
<li id="point">:</li>
<li id="min"></li>
<li id="point">:</li>
<li id="sec"></li>
</ul>
</div>
use this method.
function ampmFormat(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
Then you can add day , month and year with this.
Add the following code after assigning current hour to hours var.
var timing = hours >= 12 ? 'PM' : 'AM';
hours %= 12;
if(hours == 0)
hours = 12;
$("#ampm").html(timing);
Add this line to html
<li id="ampm"></li>
Updated code -
$(document).ready(function() {
// Making 2 variable month and day
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
// make single object
var newDate = new Date();
// make current time
newDate.setDate(newDate.getDate());
// setting date and time
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
setInterval(function() {
// Create a newDate() object and extract the seconds of the current time on the visitor's
var seconds = new Date().getSeconds();
// Add a leading zero to seconds value
$("#sec").html((seconds < 10 ? "0" : "") + seconds);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the minutes of the current time on the visitor's
var minutes = new Date().getMinutes();
// Add a leading zero to the minutes value
$("#min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
// Create a newDate() object and extract the hours of the current time on the visitor's
var hours = new Date().getHours();
var timing = hours >= 12 ? 'PM' : 'AM';
hours %= 12;
if(hours == 0)
hours = 12;
$("#ampm").html(timing);
// Add a leading zero to the hours value
$("#hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clock">
<div id="Date"></div>
<ul>
<li id="hours"></li>
<li id="point">:</li>
<li id="min"></li>
<li id="point">:</li>
<li id="sec"></li>
<li id="ampm"></li>
</ul>
</div>
You can do that manually.
If ( hours > 12){
hours = hours % 12;
}
else{
hours = hours;
}
You can also add a String to go with,
var ampm = am;
If ( hours > 12){
hours = hours % 12;
ampm = pm;
}
else{
hours = hours;
ampm = am;
}
Or a boolean or whatever....
I hope, it's useful

updating javascript time every second

Basically I want to have a live clock, one that updates every second! I've looked around and couldn't find something that has worked. Here is what I have tried:
function doDate()
{
var str = "";
var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var now = new Date();
str += "Today is: " + days[now.getDay()] + ", " + now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear();
var updateTime = function() { setTimeout("doDate()", 1000); }
document.getElementById("todaysDate").innerHTML = str;
}
This does not seem to work! I presume there is something I have done right in here?
Please modify your code as follow:-
function doDate()
{
var str = "";
var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var now = new Date();
str += "Today is: " + days[now.getDay()] + ", " + now.getDate() + " " + months[now.getMonth()] + " " + now.getFullYear() + " " + now.getHours() +":" + now.getMinutes() + ":" + now.getSeconds();
document.getElementById("todaysDate").innerHTML = str;
}
setInterval(doDate, 1000);
<div id="todaysDate"></div>
This line of code has no effect:
var updateTime = function() { setTimeout("doDate()", 1000); }
You define function variable updateTime which make postponed invocation of doDate, but this variable is unused in your code.
Instead of this you have to call setTimeout immediately without wrapping it with function:
setTimeout(doDate, 1000);
following code might help you
function doDate()
{
var str = "";
var now = new Date();
str = now.toDateString() +' '+now.toLocaleTimeString() ;
document.getElementById("todaysDate").innerHTML = str;
}
setInterval(doDate, 1000);
Your setTimeout call is incorrect:
var updateTime = function() { setTimeout("doDate()", 1000); }
Should rather look like:
setTimeout(doDate, 1000);
When adding a callback, you should not call the function (and in this case, you should not add it as a string), add the function itself.
And the function you wrap it inside of is not needed, just call the setTimeout function right away.
function doDate() {
let currentDate = document.getElementById('currentDate');
let current = new Date();
currentDate.innerHTML = `Current Date and Time : <b>${current}</b> `;
}
setInterval(doDate, 1000);
<div id="currentDate"></div>

about 24 hours and 12 hours [duplicate]

This question already has answers here:
jQuery - Change 1-24 hour to 1-12 hour using .getHours() method?
(2 answers)
Closed 9 years ago.
I want to change my hours into 12hrs not 24hrs.
this is my code :
$(document).ready(function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var newDate = new Date();
newDate.setDate(newDate.getDate());
$('#Date').html(dayNames[newDate.getDay()] + " " + newDate.getDate() + ' ' + monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear());
setInterval(function() {
var seconds = new Date().getSeconds();
$("#sec").html((seconds < 10 ? "0" : "") + seconds);
}, 1000);
setInterval(function() {
var minutes = new Date().getMinutes();
$("#min").html((minutes < 10 ? "0" : "") + minutes);
}, 1000);
setInterval(function() {
var hours = new Date().getHours();
$("#hours").html((hours < 10 ? "0" : "") + hours);
}, 1000);
});
You are looking for this
newHours = (oldHours) % 12
if (newHours == 0) {
newHours = 12;
}

How do I convert inline JS coding into an external style sheet?

I have JS code in both the body and head portions of my page. If I wanted to have them be in an external .js file, how would I move them over and then call them back onto the page?
Head -
<script language="Javascript">
setInterval("settime()", 1000);
function settime () {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var cursec = curtime.getSeconds();
var time = "";
if(curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
(curmin < 10 ? "0" : "") + curmin + ":" +
(cursec < 10 ? "0" : "") + cursec + " " +
(curhour > 12 ? "pm" : "am");
document.date.clock.value = time;
}
</script>
Body -
<script language="JS" type="text/javascript">
var monthArray = new Array("January", "February", "March", "April", "May",
"June", "July", "August", "September",
"October", "November", "December");
var today = new Date();
var todayMonth = today.getMonth();
var todayDate = today.getDate();
var todayYear = today.getFullYear();
document.write(monthArray[todayMonth] + " " + todayDate + ", " + todayYear);
</script>
Move your JS code into an external file (say, my.js) and include it within your page as :
<script type="text/javascript" src="my.js"></script>
Of course, the above assumes that my.js lies in the same folder/directory as your page. you'll need to adjust the src value as per the location of you JS file.

Categories

Resources