This question already has answers here:
How do I get the current time only in JavaScript
(23 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I wanna show the time when the user clicks on the button but it doesn't work. I used the Date() function.
function time() {
document.getElementById("datebtn").innetHTML = getDate();
}
<p id="datebtn">time is =</p>
<button type="button" onclick="time()">click to show the time</button>
To access the current date, you use new Date() in JavaScript. However, you'd probably want to format it so you get hours:minutes:seconds. So we make a new date object and format it like so:
var currentdate = new Date();
var timenow = + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Also you have a typo: It's innerHTML not innetHTML.
innerHTML removes the html inside (that is in this case all the html between <p id="datebtn"> and </p>) and replaces it with the text you give it. So you'd have to include the prefix text too if you want to use it:
document.getElementById("datebtn").innerHTML="time is ="+timenow;
Sow the final code becomes
function time() {
var currentdate = new Date();
var timenow = + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
document.getElementById("datebtn").innerHTML = "time is ="+timenow;
}
<p id="datebtn">time is =</p>
<button type="button" onclick="time()">click to show the time</button>
Hope this will help:
You have to use functions to get hour, minutes and seconds from date object.
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function time() {
var date = new Date();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
// adding 0 for single digits
mm = checkTime(mm);
ss = checkTime(ss);
document.getElementById('datebtn').innerHTML = hh + ":" + mm + ":" + ss;
}
<p id="datebtn">time is =</p>
<button type="button" onclick="time()">click to show the time</button>
This allows you to get the current date and time and use it how you want, from alerts to mails..
<SCRIPT>
var now=new Date(); // neccessary
var day=now.getDate(); // Day
var month=now.getMonth()+1; // Month (+1 because january = 0)
var year=now.getFullYear(); // Year
var seconds = now.getSeconds(); // Seconds
var minutes = now.getMinutes(); // Minutes
var hour = now.getHours(); // Hours
document.write("",day,"/",month,"/",year," - ",hour,":",minutes,":",seconds); // prints "13/04/2018 - 18:37:32"
</SCRIPT>
EDIT: so as I got downvoted for helping, here's the best thing I can think of right now, because I clearly don't know more. it is the simpliest I can think of.
<p id="time">Getting the current time..</p>
<button onclick="showTime()">Show Time</button>
<script type="text/javascript">
function showTime(){
var now=new Date();
var seconds = now.getSeconds();
var minutes = now.getMinutes();
var hour = now.getHours();
document.getElementById('time').innerHTML = hour + ":" + minutes + ":" + seconds;
}
</script>
Related
I have been following Convert a Unix timestamp to time in JavaScript thread for answer but looks like single digit time (0-9) is parsed as it is. The accepted answer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
We get like 2:3:9 instead of 02:03:09. How to get rid of this behaviour? Also can anyone please elaborate on how to get am/pm along with time?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
I think I will leave the am:pm bit to you. Press ctrl-shift j and play with your code in the console right here
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
This might be easier to understand. I have kept it closer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
I think you have to get rid of the substr-part, since the value should already be correct.
Note: you need to check if the values are already above 9, because you don't need to append anything when it is above 9.
Example
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
I want to add that these kinds of problems can be easily resolved with using a good library like moment.js
I use Date object to create time in my Javascript code and it should be formated like so : 08:04:21. This is how I tried to do it:
$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});
But when Time is logged in console string looks like this 8:1:1467844916075. Same happens when i try this:
var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();
It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object
$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});
But Time in this case looks like this: 1467785566719. Any idea how to get human readable current time(not date) plus one minute?
You can check this:
Date.getTime() returns you the number of milliseconds since 1970/01/01.
So just grab it and add 1 minute to it to form new milliseconds count for new date.
var d = new Date();
var millisecondssince1970 = d.getTime();
var newMillisec = millisecondssince1970 + (1000 * 60);
var newDate = new Date(newMillisec);
console.log(newDate.getHours() + ":"
+ newDate.getMinutes() + ":"
+ newDate.getSeconds());
Please try this,
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Here is working example https://jsfiddle.net/oa7j3krs/2/
$('#time').click(function(){
var d = new Date($.now()+60*1000); // current time + 60s
$(this).val(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
});
Anyway, I found a way to do this. Maybe it's not the best but it will do the job.
$('#time').click(function(){
var currentTime = new Date();
var addOneMinute = currentTime.getMinutes();
addOneMinute=parseInt(addOneMinute) + 1;
var Time=currentTime.getHours() + ":"
+ addOneMinute + ":"
+ currentTime.getSeconds();
console.log(Time);
$(this).val(Time);
});
I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.
I am trying to get a date to refresh on a page so I don't have to go and manually refresh it everyday. I have this code in place, but it doesn't seem to be working. The date displays, but it doesn't update when the day changes. For reference, this is being used on a BrightSign display. Can anyone tell me what I'm doing wrong? I'm kind of a JavaScript beginner so nothing too complex :)
<script type="text/javascript">
<!--
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
setInterval(clockTick, 1000);
return (month + "/" + day + "/" + year);
}
document.write(clockTick());
//-->
</script>
You will want to take the setInterval out of the function and set the time on the page inside the function so that it refreshes every second:
function clockTick() {
var currentTime = new Date(),
month = currentTime.getMonth() + 1,
day = currentTime.getDate(),
year = currentTime.getFullYear(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
seconds = currentTime.getSeconds(),
text = (month + "/" + day + "/" + year + ' ' + hours + ':' + minutes + ':' + seconds);
// here we get the element with the id of "date" and change the content to the text variable we made above
document.getElementById('date').innerHTML = text;
}
// here we run the clockTick function every 1000ms (1 second)
setInterval(clockTick, 1000);
<span id="date"></span>
you can try this:call clockTick() from outside.
function clockTick() {
currentTime = new Date();
month = currentTime.getMonth() + 1;
day = currentTime.getDate();
year = currentTime.getFullYear();
// alert("hi");
document.getElementById('date').innerHTML=month + "/" + day + "/" + year;
}
setInterval(function(){clockTick();}, 1000);//setInterval(clockTick, 1000); will also work
<div id="date"></div>
I (a javascript newbie) want to have mutiple clocks with different time values in one page.
I managed to get the clock running, but if i add a second clock only one clock is getting displayed. In the console both ids with the correct (different) time are printed.
(function($, undefined) {
$.fn.clock = function(currentTime) {
return this.each(function() {
var localTime = +Date.now();
var timeDiff = currentTime - localTime;
updateClock = function (self, diff) {
var realtime = +Date.now() + diff;
var date = new Date(realtime);
var hours = date.getHours();
if(hours < 10) hours = "0"+hours;
var minutes = date.getMinutes();
if(minutes < 10) minutes = "0"+minutes;
var seconds = date.getSeconds();
if(seconds < 10) seconds = "0"+seconds;
var day = date.getDate();
var month = date.getMonth()+1;
var year = 1900 + date.getYear();
if(day < 10) day = "0"+day;
if(month < 10) month = "0"+month;
var formattedTime = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ':' + seconds;
self.text(formattedTime);
console.log(self.attr("id")+":"+formattedTime);
setTimeout(function() {updateClock(self, diff)}, 1000);
};
updateClock($(this), timeDiff);
});
};
return this;
})(jQuery);
Call (takes time in ms as parameter):
<script type="text/javascript">
$(document).ready(function() {
$("#clock").clock(123456789);
$("#clock2").clock(1234567899);
});
</script>
clock and clock2 are empty divs.
Problem: Only clock2 (the last initialized clock) is displaying the time.
EDIT:
DIVs:
<div id="clock"/>
<div id="clock2"/>
EDIT2:
It's working now. The divs need an end-tag.
updateClock is a implicitly global variable. Add a var, or make it
function updateClock(self, diff) {
to scope the function correctly.
Div's must have end tag
Tag omission None, both the starting and ending tag are mandatory.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div
<div id="clock"></div>
<div id="clock2"></div>