How can I get javascript to write dates in my input boxes? - javascript

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)
})

Related

Get Date string value from Date and Time field in CRM using JavaScript

I am trying to get the date string value(mm/dd/yyyy)from a custom date and time field and set the returned value back into the custom field. I found this script and modified it but it does not seem to work. When I step through the code it breaks on var year = startDate.getFullYear() + ""; Any ideas what I am doing wrong? Thanks.
function ConcatChainsAuth() {
var startDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
if (startDate != null) {
var year = startDate.getFullYear() + "";
var month = (startDate.getMonth() + 1) + "";
var day = startDate.getDate() + "";
var dateFormat = month + "-" + day + "-" + year;
Xrm.Page.getAttribute("new_dateauthorized").setValue(dateFormat);
}
var lookupObject = Xrm.Page.getAttribute("new_chain");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Chain = lookUpObjectValue[0].name;
}
}
var lookupObject = Xrm.Page.getAttribute("new_package");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Package = lookUpObjectValue[0].name;
}
}
var concatedField = Chain + "-" + Package + "-" + dateFormat;
Xrm.Page.getAttribute("new_name").setValue(concatedField);
Xrm.Page.data.entity.save();
}
Assuming that new_dateauthorized is a CRM date field, then Xrm.Page.getAttribute("new_dateauthorized").getValue() will return a Date object.
In which case you can just manipulate the Date object, like so:
var currentDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
currentDate.setMonth(currentDate.getMonth() + 1);
Xrm.Page.getAttribute("new_dateauthorized").setValue(currentDate);
However, adding months in this fashion fails in some cases, check out the comments here for more info.

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>

How to set datetimepicker to localtime when posting form

I have a problem when i am posting a editform with a datetime value in it. I have a script that sets the localdatetime with getTimeZonOffset. The first time when i want the utc time from the database to be displayed in localtime it works. The problem is when i want to edit the form with a datetimepicker. The new value gets stored in the database and every time the user hits the submit button it adds the localtime again.
How can i do to avoid this?
$(function () {
// Determine timezone offset in milliseconds
var d = new Date();
var offsetms = d.getTimezoneOffset() * 60 * 1000;
$('.UTCTime input').each(function () {
try
{
var text = $(this).val();
var n = new Date(text);
n = new Date(n.valueOf() - offsetms);
var curr_date = n.getDate();
var curr_month = n.getMonth() + 1; //Months are zero based
var curr_year = n.getFullYear();
var curr_hour = n.getHours();
var curr_minutes = n.getMinutes();
$(this).val(curr_year + "/" + curr_month + "/" + curr_date + " " + curr_hour + ":" + curr_minutes);
}
catch (ex) {
console.warn("Error converting time", ex);
}
});
});
$(function () {
$(".datetimepicker input").datetimepicker({
dateFormat: "yy/mm/dd",
showTime: true,
});
});
<div class="span3 value UTCTime datetimepicker">
It looks like your script will override any value already saved when you edit it
You need to add some kind of check when setting the datetime value so you dont override it
if( !$(this).val() ) {
$(this).val(curr_year + "/" + curr_month + "/" + curr_date + " " + curr_hour + ":" + curr_minutes);
}
You might have to change the if-condition if you have some other default value
Make unique index in your database for userid and timezone, that means that the current time zone can not be re entered again for the same user it can be updated.
If you have mysql db then use insert into table on duplicate key update....
Hope this will give you the correct idea.

Javascript date format for a date

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

Categories