This question already has answers here:
Leading zeros in minutes
(6 answers)
Closed 8 years ago.
I have a clock made that displays the current time in Hours:Minutes:Seconds. Currently the time is displayed as so 20:30:25, but my problem is that when the time is a single digit for example 1.05 (3 seconds) am, it will appear like this on the clock 1:5:3. I want it to appear like this 01:05:03.
How can this be done?
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
today = hours+':'+minutes+':'+seconds;
document.write(today);
A simple way is to use a slice(-2) trick to always let the number with a preceding zero (if needed)
Slice, with a negative parameter, takes the last n characters of a string, in this case, always a two digit value:
var today = new Date();
var hours = ("00" + today.getHours()).slice(-2);
var minutes = ("00" + today.getMinutes()).slice(-2);
var seconds = ("00" + today.getSeconds()).slice(-2);
alert(hours+":"+minutes+":"+seconds);
Simply add zeros! I used ternary operator to do it.
var today = new Date();
var hours = today.getHours() <10 ? "0"+today.getHours(): today.getHours();
var minutes = today.getMinutes() <10 ? "0"+today.getMinutes(): today.getMinutes();
var seconds = today.getSeconds() <10 ? "0"+today.getSeconds(): today.getSeconds();
today = hours+':'+minutes+':'+seconds;
document.write(today);
Related
This question already has answers here:
How can I subtract hours from a HH:MM AM time string in Javascript?
(7 answers)
Closed 1 year ago.
I have 2 strings, that have the minute and hour that a function needs to occur at.
I want to check, if the minute and hour which are specified in string format, and from my database are within 5 minutes of the current time, call this function.
My original thought was something like:
(today.minute is the current minute)
today.minute:
minute = "55"
hour = "14"
var today = new Date();
var time = today.getMinutes(), today.getHours()
if (today.getMinutes() - 5 == minute) {
myFunc()
}
But that isn't going to work, because I need the hour and minute - 5 minutes... how can I do this?
Is this what you are looking for?
let minute = "55"
let hour = "14"
let today = new Date();
//var time = today.getMinutes(), today.getHours()
if (Math.abs(today.getMinutes() - Number(minute)) <= 5) {
myFunc()
}
function myFunc() {
console.log('myFunc called', today.getMinutes());
}
This question already has answers here:
getMinutes() 0-9 - How to display two digit numbers?
(21 answers)
Closed 3 years ago.
I would like to get it to display 0 infront of the output if it's under 10.
const time = new Date();
let hour = today.getHours();
let minute = today.getMinutes();
let second = today.getSeconds();
if (second < 10) {
second = 0 + second;
}
console.log(`Time is ${hour} : ${minute} : ${second}`);
Instead of showing for example 19:5:7, I would like to see 19:05:07
///
Ok, I found out what the problem was. 0 was a number not a string. Just started with JS.
Thanks for the help!
You could pad the value with leading zeroes.
const pad2 = s => s.toString().padStart(2, '0');
let today = new Date;
let hour = pad2(today.getHours());
let minute = pad2(today.getMinutes());
let second = pad2(today.getSeconds());
console.log(`Time is ${hour}:${minute}:${second}`);
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>
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.
Working on a javascript-canvas based clock (classic analog clock view), also displaying the current date below the clock.
I already have this code to get the current time in javascript:
// get current time
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes + seconds / 60;
Works great, except that I don't know how to get the number in seconds until the end of the day, so I could run an ajax request at 00:00h to update the current date.
The question is, how to get easily the number in seconds until end of the day in javascript?
I plan to start a setTimeout()-function after the clock loaded with the number of seconds left, to update the date when needed.
I'm assuming the date you want to change is not from these values. You need to change it in some place not directly related to this clock?
I would suggest to add a function to check if the day has changed and include it when the clock is refreshed.
In any case, getting the seconds to the end of the day should be something like
var secondsUntilEndOfDate = ( (24*60*60) - ( (hours*60*60) + (minutes*60) + seconds ) );
Javascript:
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var secondsUntilEndOfDate = (24*60*60) - (h*60*60) - (m*60) - s;
For GMT+0 it would be
const secondUntilEndOfTheDay = 86400 - Math.floor(new Date() / 1000) % 86400;