I'm trying to use the current month, year, month-year and day-month in my html page.
This is the javascript I'm using
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var n = new Date();
var y = n.getFullYear();
var m = n.getMonth();
var d = n.getDate();
document.getElementById("date").innerHTML = d + " " + months[m] + " " + y;
document.getElementById("month-year").innerHTML = months[m] + " " + y;
document.getElementById("day-month").innerHTML = d + " " + months[m];
document.getElementById("year").innerHTML = y;
document.getElementById("month").innerHTML = months[m];
document.getElementById("day").innerHTML = d;
I'm using an html <a> tag to call the date, month, year etc, as follows
<a id="date"></a>
<a id="month-year"></a>
<a id="day-month"></a>
<a id="year"></a>
<a id="month"></a>
<a id="day"></a>
However it only works when I use <a id="date"></a> somewhere in the page, if I don't use <a id="date"></a> then none of the other tags work.
I've created a jsfiddle to highlight the problem. If you remove <a id="date"></a> from the Html section you'll see the problem I'm referring to.
Thanks to the answer below
Full code can be seen at jsfiddle
It's because your javascript is breaking due to null object on
document.getElementById("date").innerHTML = d + " " + months[m] + " " + y;
You should check whether it exists before setting the innerHTML. For example:
var dateObject = document.getElementById("date");
if (dateObject) dateObject.innerHTML = d + " " + months[m] + " " + y;
Related
<!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>
I have been trying to get the months full name using the script (shown below) but couldn't able to get it.. seems like some thing is missing..
Code as follows:
var d=new Date();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var timeString = d.getDate() + '-' + d.getFullYear()
+ ' ' + d.getHours() + ':' + d.getMinutes() + ':'
+ d.getSeconds();
document.getElementById("date").innerHTML = (monthNames[d.getMonth()]) + timeString;
<div>
<small><B><p id="date" name="date" class="date"></p></B></small>
</div>
Any Help is Appreciated..
var d=new Date();
Date.prototype.getMonthName = function() {
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
return monthNames[this.getMonth()];
}
var timeString = d.getDate() + '-' + d.getMonthName() + '-' + d.getFullYear()
+ ' ' + d.getHours() + ':' + d.getMinutes() + ':'
+ d.getSeconds();
document.getElementById("date").innerHTML =timeString;
Your code is OK
There is one simple issue when creating timeString variable. Instead monthNames you should invoke your method "getMonthName" instead just asking for variable you created inside getMonthName.
var timeString = d.getDate() + '-' + d.getMonthName() + '-' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
Here is a little fiddle that does what you want.
<div>
<p id="date" name="date" class="date">Date</p>
</div>
<script>
Date.prototype.getMonthName = function() {
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return monthNames[this.getMonth()];
};
var d = new Date();
var monthName = d.getMonthName();
var timeString = d.getDate() + '-' + monthName + '-' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
document.getElementById("date").innerHTML = timeString;
</script>
Notice setting date and time in your paragraph is outside of prototype declaration. Also beware of return statement (code after it won't execute)!
I am trying to edit some JavaScript code which basically shows tomorrow's date. However for Friday and weekends (Friday, Saturday and Sunday) it should show the following Monday's date.
Here is the code I have:
var date = new Date(); // timezone
date.setDate(date.getDate() + 1); // move to tomorrow
date.setUTCHours(11,0,0,0); // set time using UTC(GMT) timezone
document.getElementById("next-shipment").textContent = date.toLocaleString();
JSFiddle
For example let say today is Tuesday, November 4, 2015. The javascript code should show "November 5, 2015"---> in this format.
On Friday, Saturday,and Sunday the code should show: Next Monday's date: November 9, 2015
The code should work all year around.
Try this:
var today = new Date(); // timezone
document.getElementById("result").innerHTML = "<br/>Today's next day is: " + FormatDate(GetNextDay(today));
function GetNextDay(date){
date.setDate(date.getDate() + 1); // move to next day.
switch(date.getDay()) {
case 0: //Sunday
case 6: //Saturday
date = GetNextDay(date);
}
return date;
}
function FormatDate(date){
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
}
function TestDate(){
var date = new Date(document.getElementById("TestDate").value);
document.getElementById("result").innerHTML += "<br/>Selected day's next day is: " + FormatDate(GetNextDay(date));
}
<input type="text" id="TestDate" value="November 06, 2015" />
<input type="button" value="Get Next Day" onclick="TestDate();" />
<div id="result"></div>
The idea is fairly simple:
The first two lines and the TestDate() function at the end are only for testing and you don't need them in your code.
The job is mainly done by the GetNextDay() function. You give it a date and it calculates and give you back the next date (skipping the weekend). It does that in two steps:
1- First it adds one day to the given date date.setDate(date.getDate() + 1);.
2- It checks the day of the new date date.getDay(). If it is 6 or 0 (Saturday or Sunday) it calls itself again date = GetNextDay(date); which means it will add one more day to the date. This concept of a function calling itself is called "recursion" in programming. When it reaches Monday, it will stop calling itself and return the date.
The only way to calculate the next day properly is by adding one day to the date. This utilizes JavaScript's Date library which knows how to do the calculation. For example, it knows that adding one day to "November 30" is "December 1", NOT "November 31". If we try to do that manually by adding 1 to number of the day: 30 + 1 = 31, but "November 31" is not a valid date. To solve this issue, we will need to write a library similar to the one that JavaScript has. Obviously, this is like reinventing the wheel and there is no point in that.
The Date constructor also has a function called getDay() which returns a integer between 0 and 6 (0 = Sunday, 6 = Saturday). You can use this to detect Friday(0), Saturday(6), Sunday(0) and omit them.
Here is a demo that alerts you if it's the weekend:
var myDate = new Date();
myDate.setFullYear(2015);
myDate.setMonth(11);
myDate.setDate(6);
if(myDate.getDate() == 5 || myDate.getDay() == 6 || myDate.getDay() == 0) alert('Weekend!');
document.write(myDate);
To find the next day, pass the Date constructor a time & it will do the work for you. You will need to create an array however to format it in the way you want November, 5 2015.
JS:
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var tomDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var day = tomDate.getDate();
var month = monthNames[tomDate.getMonth()];
var year = tomDate.getFullYear()
var d = new Date();
var n = d.getDay();
if(n == 5){
var fromFri = n + 4;
document.write("<b>" + month + " " + fromFri + ", " + year + "</b>");
}else if (n == 6){
var fromSat = n + 3;
document.write("<b>" + month + " " + fromSat + ", " + year + "</b>");
}else if (n == 0) {
var fromSun = n + 2;
document.write("<b>" + month + " " + fromSun + ", " + year + "</b>");
}else{
document.write("<b>" + month + " " + day + ", " + year + "</b>");
}
Updated: CODEPEN DEMO
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>
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.