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. :-)
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>
My js project is working fine but I need to exclude Saturdays and Sunday in it, or even holiday. Can you please check on my code on how can I achieve this.
<p>Meet me at <span id="thedate"></span></p>
<script>
var m_names = ["January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December"
];
var d_names = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
var curr_date = myDate.getDate();
var curr_month = myDate.getMonth();
var curr_day = myDate.getDay();
document.getElementById("thedate").innerHTML = (d_names[curr_day]
+ "," + m_names[curr_month] + " " + curr_date);
</script>
You could easily find out if the day is not between monday - friday by:
// Sunday - Saturday : 0 - 6
if (curr_day < 1 || curr_day > 5) {
// do something, maybe set it to monday?
curr_day = 1
}
I am trying to display current date by finding string and replacing with current date, its working fine, but additionally I want to display another date where if string has some comma seprated value then it will add to the current date and will display accodrdingly, So lets say if I add (,30) in string it will add 30 days additional in current date and display
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>
Try this code :
var setCurrentDate = function() {
var disclaimerStr = $(".dynamic-date").html(),
currDateStr = "{currentdate}",
date = new Date(),
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
currDate =
months[date.getMonth()] +
" " +
date.getDate() +
", " +
date.getFullYear(),
newDisclaimerStr;
if (disclaimerStr.indexOf(currDateStr) != -1) {
newDisclaimerStr = disclaimerStr.replace(currDateStr, currDate);
$(".dynamic-date").html(newDisclaimerStr);
}
var reg = new RegExp(/\{currentdate(,(\d+))\}/);
var currDateStr2 = '{currentdate,30}'; // you need to change here!
var days = parseInt(reg.exec(currDateStr2)[2], 10);
console.log(days) //30
var date2 = new Date();
date2.setDate(date2.getDate() + days);
console.log(date2) // "2019-04-27T09:13:00.789Z"
};
setCurrentDate();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-date">
<b>Current Date</b> : {currentdate} <br><br>
<b>Extended Date</b> : {currentdate,30} <br><br>
</div>
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 know there are a few similar posts about this topic, but none were helping me much (or maybe that's cause I'm still a newbie).
Anyway, the thing I'm looking for is a script to show me the day and date + 11 days from now.
The script below is what I use to show the current day & date. So I figured there has to be some simple line to add or modify somewhere? like "+11"
Any helpful answer would be very very very much appreciated!
var daynames = 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 currentTime = new Date();
var dayname = currentTime.getDay();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var year = currentTime.getFullYear();
document.write(daynames[dayname] + "<BR> " + day + " " + months[month] + " " + year);
Assuming you are working on JavaScript, this snippet will set d to +11 days from current day -
var d = new Date();
d.setDate(d.getDate()+11);
Assuming javascript because of document.write
var yourDate=new Date();
yourDate.setDate(yourDate.getDate()+11); //11 is the number of days you want to add
Refer: getDate and setDate