solving the [object Object] issue - javascript

I'm trying to separate concerns using modules in Js eveything is going Ok except that I want to display the time of the system and I did that too but when I output it I got an [object Object] string and what proves me right that really I got the right system Time is that when I console logged the interCtrl.getTheTime I got the time of the system and here is a screenshot:
here is my code to let you understand better:
JS:
var controller = (function(interCtrl, UICtrl) {
//1.get the time
setInterval(document.querySelector(".Time").innerHTML = interCtrl.getTime(),100);
// console.log(interCtrl.getTime());
//2.get the date
document.querySelector(".subDate").innerHTML = interCtrl.date();
};
document.querySelector(".add__btn").addEventListener("click", ctrlAddPlans);
document.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
ctrlAddPlans();
}
});
})(internalController);
var internalController = (function() {
//some code
function getTheDate() {
var newDate;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth() + 1;
// var x=1;
if (month.toString().length < 2) {
month = " 0" + month + " ";
}
var date = " %11%/%04%/%2019%";
newDate = date.replace("%11%", day + " ");
newDate = newDate.replace("%04%", month);
newDate = newDate.replace("%2019%", " " + year);
return newDate;
}
function getTheTime() {
//.get the timeDiv
// const timeDiv =
//.get the time (h,m,s)
var date = new Date();
var hours = date.getHours();
if (hours.toString().length < 2) {
hours = `0${hours}`;
}
var mins = date.getMinutes();
if (mins.toString().length < 2) {
mins = `0${mins}`;
}
var seconds = date.getSeconds();
return {
time: hours+ " : "+ mins+" : "+seconds
};
}
return {
date: function getDate() {
return getTheDate();
},
getTime: function getTime() {
return getTheTime();
}
};
})();
I saw this question but it didn't help me what does [object Object] mean?
so any help please and thank you in advance

The output of the getTime function is an object. To make it output a string, you can change its return statement from
return {
time: hours+ " : "+ mins+" : "+seconds
};
to
return hours + " : " + mins+" : " + seconds;
Or, alternatively, if you want it to be an object, you'll have to access its time property to get the value. Like
var timeObj = interCtrl.getTheTime();
var timeString = timeObj.time;

Related

log file not created when date change nodejs

i have problem when i try make log for everytime date change it make new file and stop log when end date , for example
20200709_Chatlog.txt for
2020-07-09 21:56:12:91 - connect null
2020-07-09 21:56:15:952 - a user connected
20200710_Chatlog.txt for
2020-07-10 21:56:12:91 - connect null
2020-07-10 21:56:15:952 - a user connected
but my file is always overwrite in the same file date like this
20200709_Chatlog.txt
2020-07-09 21:56:12:91 - connect null
2020-07-09 21:56:15:952 - a user connected
2020-07-10 21:56:12:91 - connect null
2020-07-10 21:56:15:952 - a user connected
, but everytime i restart the server new file created
my code is
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function logDate(){
var d = new Date();
var yy = addZero(d.getFullYear());
var mm = addZero(d.getMonth() + 1);
var dd = addZero(d.getDate());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
var ms = addZero(d.getMilliseconds(), 3);
var tanggal = "";
return tanggal = +yy+ "-" +mm+ "-" +dd+ " " +h+ ":" +m+ ":" +s+ ":" +ms + " ";
}
function fileDate(){
var d = new Date();
var yy = addZero(d.getFullYear());
var mm = addZero(d.getMonth() + 1);
var dd = addZero(d.getDate());
var tanggal = "";
return tanggal = +yy+ "" +mm+ "" +dd+ "_";
}
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream(fileDate()+'Chatlog.txt', { flags: 'a' }); // 'w' to truncate
var logStdout = process.stdout;
console.log = function () {
logFile.write(logDate()+" - " + util.format.apply(null, arguments)+ '\n');
logStdout.write(logDate()+" - " + util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
am i do something wrong, please help , and thanks for helping , sorry if my english bad

JavaScript clock not displaying properly

I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>
You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);
You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.
Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>
setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>

Javascript Date constructor ignoring parameters

Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong? Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below: and a jsfiddle
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the full year of todays date.</p>
<p id="demo2">todays date.</p>
<p id="demo3">some other date.</p>
<button onclick="showdates()">Try it</button>
<script>
function showdates() {
var d = Date.now();
var dv = document.getElementById('demo');
dv.innerHTML = d;
var pd = prettyDate(d);
dv = document.getElementById('demo2');
dv.innerHTML = pd;
var ts = prettyDateToTimeStamp(pd);
dv = document.getElementById('demo3');
dv.innerHTML = ts;
}
function prettyDate(javaScriptTimeStamp) {
var dt = new Date(javaScriptTimeStamp);
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
console.log("halves: " + halves);
var calpart = halves[0];
console.log("calpart : " + calpart );
var clockpart = halves[1];
console.log("clockpart : " + clockpart );
var calbits = calpart.split('/');
console.log("calbits : " + calbits );
var timebits = clockpart.split(':');
console.log("timebits : " + timebits );
var year = parseInt(calbits[2],10);
console.log("year : " + year );
var month = parseInt(calbits[0],10);
console.log("month : " + month );
var day = parseInt(calbits[1],10);
console.log("day : " + day );
var hour = parseInt(timebits[0],10);
console.log("hour : " + hour );
var min = parseInt(timebits[1],10);
console.log("min : " + min );
var sec = parseInt(timebits[2],10);
console.log("sec : " + sec );
month += 3; // change month radically to demonstrate the problem
console.log("month is now: " + month );
day += 7; // change day too
console.log("day is now: " + day );
var ts = Date(year,month,day,hour,min,sec,0);
console.log("ts : " + ts ); // date ctor paramters completely ignored...?
return ts;
}
</script>
</body>
</html>
omg, I have to say "new" Date .... (I've been using Python too much lately)
corrected code now works.
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
var calpart = halves[0];
var clockpart = halves[1];
var calbits = calpart.split('/');
var timebits = clockpart.split(':');
var year = parseInt(calbits[2],10);
var month = parseInt(calbits[0],10);
var day = parseInt(calbits[1],10);
var hour = parseInt(timebits[0],10);
var min = parseInt(timebits[1],10);
var sec = parseInt(timebits[2],10);
month += 3; // change month radically to demonstrate the problem
day += 7; // change day too
var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
return ts;
}

javascript change textbox value onchange

I have a StartDate and an ExpiryDate textbox. Both take values in the forms of 10/12/2013.
What I would like to be able to do is, when you change the StartDate textbox (whether from empty or just updating the date) the ExpiryDate textbox needs to add 1 year onto the date.
Example:
If StartDate = 10/12/2013 then ExpiryDate will automatically change to 10/12/2014.
How to do that with JS?
function MyFunc() {
MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
MyTextBox2 = document.getElementById("<%= TextBox2.ClientID %>");
var date = new Date(MyTextBox.value);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() + 1;
MyTextBox2.value = day + "/" + month + "/" + year;
}
Try this, call the setExpiryDate() function whenever you need to set the expiration date.
function setExpiryDate() {
var txtStartDate = document.getElementById("ctrl1");
var txtExpiryDate = document.getElementById("ctrl2");
var dt = new Date(txtStartDate.value);
if (!isNaN(dt)) {
dt = dt.setYear(dt.getYear() + 1);
txtExpiryDate.value = padStr(temp.getDate()) + '/' + padStr(temp.getMonth() + 1) + '/' + temp.getFullYear().toString();
}
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
How about this:
function updateInput(value){
document.getElementsById('Yourelement').Value = value;
}
Other than that, all you need is some date parsing/string manipulation to find the correct year.

Unique ID that gets a date in specific format?

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I want it to add 1 each time the generateid button is clicked. so it will change to 0002. Here is the current code I have. Is there a function that can grab the date automatically?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
function Month() {
var m = new Date();
var mm = m.getMonth() + 1;
if (mm < 10) {
mm = '0' + mm;
return mm;
}
}
function Year() {
var y = new Date();
var yy = y.getFullYear();
return yy;
}
function Day() {
var d = new Date();
var dd = d.getDate();
return dd;
}
//generate id
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator();
document.getElementById("generateid").disabled = true;
}
You can use the following object:
var idGenerator = {
seq: 0,
generateId: function () {
this.seq++;
return (new Date()).toISOString().substring(0, 10) + '-' + ('000' + this.seq).substr(-4)
}
}
after declaration like this, try
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + idGenerator.generateId();
document.getElementById("generateid").disabled=true;
}
If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.
jsfiddle
var ttlIds = 0;
function guidGenerator() {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4());
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
//document.getElementById("generateid").disabled=true;
ttlIds++;
if(ttlIds < 10){
ttlIds_formatted = '000'+ttlIds;
}else if(ttlIds < 100){
ttlIds_formatted = '00'+ttlIds;
}else if(ttlIds < 1000){
ttlIds_formatted = '0'+ttlIds;
}
d = new Date();
var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
document.getElementById("funkydate").value = funkydate;
}

Categories

Resources