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>
Related
var today = new Date();
var day = today.getDay()
var month = today.getMonth();
var year = today.getFullYear()
var date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
function dateTimeClock() {
$('#today').text(today);
$('#day').text(day);
$('#month').text(month);
$('#year').text(year);
$('#date').text(date);
$('#time').text(time);
$('#dateTime').text(dateTime);
}
setInterval(dateTimeClock, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<p id="today"></p>
<p id="day"></p>
<p id="month"></p>
<p id="year"></p>
<p id="date"></p>
<p id="time"></p>
<p id="dateTime"></p>
Can someone please tell why my setInterval is not kicking in ?
I expect my data to refresh every second.
the var for date is defined outside of the interval so it doesn't update. to fix this you'll have to include it in your dateTimeClock function
function dateTimeClock() {
var today = new Date();
var day = today.getDay()
var month = today.getMonth();
var year = today.getFullYear()
var date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
$('#today').text(today);
$('#day').text(day);
$('#month').text(month);
$('#year').text(year);
$('#date').text(date);
$('#time').text(time);
$('#dateTime').text(dateTime);
}
setInterval(dateTimeClock, 1000);
Your time variables are only called once, so their value doesn't change.
Try calling the time variables from within your dateTimeClock function:
function dateTimeClock() {
var today = new Date();
var day = today.getDay()
var month = today.getMonth();
var year = today.getFullYear()
var date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date + ' ' + time;
$('#today').text(today);
$('#day').text(day);
$('#month').text(month);
$('#year').text(year);
$('#date').text(date);
$('#time').text(time);
$('#dateTime').text(dateTime);
}
setInterval(dateTimeClock, 1000);
from date selected by the datepicker in dd-mm--yy format after this i need next year date with -1 day..i.e From:29-07-2016 then To:28-07-2016 like this...please guyz help me..i m sharing my source code
$('#oldDate').on('change', function(e){
var oldDate = new Date(this.value);
$('.datepicker').datepicker({dateFormat:'dd-mm-yy'});
$('#old').html(new Date(oldDate));
oldDate.setDate(oldDate.getDate()-1);
oldDate.setFullYear(oldDate.getFullYear()+1);
var day = ("0" + oldDate.getDate()).slice(-2);
var month = ("0" + (oldDate.getMonth() + 1)).slice(-2);
var today = oldDate.getFullYear()+"-"+(month)+"-"+(day);
// var today = oldDate.(day)+"-"+(month)+"-"+getFullYear();
// alert(today);
$('#new').val(today);
<p class="left">
<label for="from">FROM:</label>
<input type="text" name="from" id="oldDate" class="datepicker"/>
</p>
<p class="pull-right">
<label for="to">TO:</label>
<input type="text" name="to" id="new">
</p>
To achieve expected result, use datepicker and then use on change function to make work
JS:
$('.datepicker').datepicker({
dateFormat: 'dd-mm-yy'
}).datepicker("setDate", "0");
$('#oldDate').click(function() {
$('#oldDate').datepicker('setDate', new Date());
});
$('#oldDate').on('change', function(e) {
console.log(this.value)
var x = this.value;
var from = x.split("-");
var f = new Date(from[2], from[1] - 1, from[0]);
var oldDate = new Date(f);
$('#old').html(new Date(oldDate));
oldDate.setDate(oldDate.getDate() - 1);
oldDate.setFullYear(oldDate.getFullYear() + 1);
console.log(oldDate)
var day = ("0" + oldDate.getDate()).slice(-2);
var month = ("0" + (oldDate.getMonth() + 1)).slice(-2);
var today = (day) + "-" + (month) + "-" + oldDate.getFullYear();
// var today = oldDate.(day)+"-"+(month)+"-"+getFullYear();
// alert(today);
$('#new').val(today);
});
Codepen-http://codepen.io/nagasai/pen/XKBZmN
Check this :
<script type="text/javascript">
var dt = new Date('2016/12/10');
var month = dt.getMonth()+1;
var day = dt.getDate()-1;
var year = dt.getFullYear()+1;
alert(month + '-' + day + '-' + year);
</script>
I made this fiddle http://jsfiddle.net/cyrtx7qw/1/ and I cant figure out how to make these two dates write on page load. I need them to check if the boxes are empty and then I want to write the today's date and today-7 respectively.
if ($('#datePickersAppearance').is(':empty')) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth();
curr_month++;
var curr_year = today.getFullYear();
document.getElementById("to").innerHTML = curr_date + "." + curr_month + "." + curr_year;
today.setDate(today.getDate() - 7);
var new_date = today.getDate();
var new_month = today.getMonth();
new_month++;
var new_year = today.getFullYear();
document.getElementById("from").innerHTML = new_date + "." + new_month + "." + new_year;
}
Also, is there a way keep another date after page reload in case I change the default ones? I need the if statement to not trigger then...
filddle
if ($('#datePickersAppearance').is(':empty'))
to
if ($('.datePickersAppearance').val() == '')
document.getElementById("from").innerHTML
should be
document.getElementById("from").value
The biggest problem is that <input> elements do not have a .innerHTML property. It is instead .value.
Your jQuery was traded for JavaScript.
Code was truncated for readability.
Use this instead:
(function loadDates(element){
var from = document.getElementById('from')
var to = document.getElementById('to')
if(!from.value.length && !to.value.length ){
var my_date = new Date()
to.value = my_date.getDate() + "." + my_date.getMonth() + "." + my_date.getFullYear()
// Redefine date object
my_date.setDate(my_date.getDate() - 7)
from.value = my_date.getDate() + "." + my_date.getMonth() + "." + my_date.getFullYear()
}//endif
})();
Updated, you can use sessionStorage to save your dates for page reloads. Also .blur() event handler is used to save data for sessionStorage, so that it's available when the page loads :-) Some other event handlers like .change() could be use as well. Fiddle
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth();
curr_month++;
var curr_year = today.getFullYear();
var toDate = "";
//check if there's a to Date in sessionStorage
if (sessionStorage.getItem("toDate")) {
toDate = sessionStorage.getItem("toDate");
sessionStorage.setItem("toDate", toDate);
} else {
toDate = curr_date + "." + curr_month + "." + curr_year;
sessionStorage.setItem("toDate", toDate);
}
document.getElementById("to").value = toDate;
today.setDate(today.getDate() - 7);
var new_date = today.getDate();
var new_month = today.getMonth();
new_month++;
var new_year = today.getFullYear();
var fromDate = "";
//check if there's a from Date in sessionStorage
if (sessionStorage.getItem("fromDate")) {
console.log("if");
fromDate = sessionStorage.getItem("fromDate");
sessionStorage.setItem("fromDate", fromDate);
} else {
// actually else part of the code never runs because there's toDate in sessionStorage.
console.log("else");
fromDate = new_date + "." + new_month + "." + new_year;
sessionStorage.setItem("fromDate", fromDate);
}
document.getElementById("from").value = fromDate;
$("#from").blur(function() {
//check that there is data before saving into sessionStorage
if (this.value.length >= 8)
sessionStorage.setItem("fromDate", this.value)
});
$("#to").blur(function() {
//check that there is data before saving into sessionStorage
if (this.value.length >= 8)
sessionStorage.setItem("toDate", this.value)
})
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>
How do I format a date in Javascript to something e.g. 'yyyy-MM-dd HH:mm:ss z'?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out for me :/
Any idea?
======
I solved my own which I rewrote like this:
var parseDate = function(date) {
var m = /^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d) UTC$/.exec(date);
var tzOffset = new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTimezoneOffset();
return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5] - tzOffset, +m[6]);
}
var formatDateTime = function(data) {
var utcDate = parseDate(data);
var theMonth = utcDate.getMonth() + 1;
var myMonth = ((theMonth < 10) ? "0" : "") + theMonth.toString();
var theDate = utcDate.getDate();
var myDate = ((theDate < 10) ? "0" : "") + theDate.toString();
var theHour = utcDate.getHours();
var myHour = ((theHour < 10) ? "0" : "") + theHour.toString();
var theMinute = utcDate.getMinutes();
var myMinute = ((theMinute < 10) ? "0" : "") + theMinute.toString();
var theSecond = utcDate.getSeconds();
mySecond = ((theSecond < 10) ? "0" : "") + theSecond.toString();
var theTimezone = new Date().toString();
var myTimezone = theTimezone.indexOf('(') > -1 ?
theTimezone.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') :
theTimezone.match(/[A-Z]{3,4}/)[0];
if (myTimezone == "GMT" && /(GMT\W*\d{4})/.test(theTimezone)) {
myTimezone = RegExp.$1;
}
if (myTimezone == "UTC" && /(UTC\W*\d{4})/.test(theTimezone)) {
myTimezone = RegExp.$1;
}
var dateString = utcDate.getFullYear() + "-" +
myMonth + "-" +
myDate + " " +
myHour + ":" +
myMinute + ":" +
mySecond + " " +
myTimezone;
return dateString;
}
and I get: 2012-11-15 22:08:08 MPST :) PERFECT!
function formatDate(dateObject) //pass date object
{
return (dateObject.getFullYear() + "-" + (dateObject.getMonth() + 1)) + "-" + dateObject.getDate() ;
}
Use this lib to make your life much easier:
var formattedDate = new Date().format('yyyy-MM-dd h:mm:ss');
document.getElementById("time").innerHTML= formattedDate;
DEMO
Basically, we have three methods and you have to combine the strings for yourself:
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
Example:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year); </script>
for more details look at 10 steps to format date and time and also check this