I made code to countdown based on the result of a current timestamp that adds up to five minutes, and I can't get the script to display the countdown from that timestamp. The code complete:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<title>Hello, world!</title>
<script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script type="text/javascript">
var duration = moment.duration(1646486515 * 1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('#time').text(moment(duration.asMilliseconds()).format('h:mm:ss'));
if(duration.asSeconds() <=0) {
window.location.replace(window.location.pathname + window.location.search + window.location.hash);
}
}, interval);
</script>
</head>
<body>
<center><p><h1>Hello, world!</h1></p></center>
<div class="container mb-2 my-2">
<div class="p-3 shadow-sm">
result of code: <span id="time" class="countdown">--:--</span>
<?php
echo '<br />NOW:'.time().'<br>+5 minutes: '.time()+300;
?>
<br />
What i want is: 00:04:59
</div>
</div>
</body>
</html>
The result:
https://i.stack.imgur.com/oNBND.png
if you give "+5 minutes", that is the sum of time() function + 300 seconds (5 minutes), you will have, for example, the date now + 5 minutes on future, but in timestamp. The intention here, is that script count 00:05:00 starting of time() now.
Look carefully at this line:
var duration = moment.duration(1646486515 * 1000, 'milliseconds');
How many minutes are there in 1646486515 seconds? A lot more than five! In fact, it is somewhere over 52 years, but when you format it you aren't showing the years, months, and days, only the remaining hours, minutes, and seconds.
That's because time() is returning you a representation of a point in time, based on the number of seconds elapsed since midnight UTC, 1st January 1970.
In order to get the duration between that point in time and another point in time, you need to compare them. The simplest way to do that is to substract one from another. For instance, 1646486815 - 1646486515 gives you 300, representing a duration of 300 seconds between those two points in time.
In your example, you know the duration is 300 seconds, so could just write that:
var duration = moment.duration(300 * 1000, 'milliseconds');
Or more simply:
var duration = moment.duration(300, 'seconds');
A second problem is on this line:
$('#time').text(moment(duration.asMilliseconds()).format('h:mm:ss'));
Here, we take a duration, and use it to create a "moment", that is a specific point in time; but what point in time, and why? What we actually wanted was to format it, because the duration type doesn't have a format method, but it has methods to get hours, minutes, and seconds, so we can just write that ourselves:
var duration = moment.duration(300, 'seconds');
formattedDuration = duration.hours() + ':' + String(duration.minutes()).padStart(2, '0') + ':' + String(duration.seconds()).padStart(2, '0');
$('#time').text(formattedDuration);
The key here is to look at each piece in turn, not get caught up trying to put the pieces together until we have things working. Once we know we can create a duration based on a number of seconds, and format that duration, we can add in the PHP to decide how many seconds to start with. Once we have that working, we can add in the part that counts that duration down, and then the part that does something extra once it reaches zero.
I ended up solving my problem with another idea. Maybe if you are searching for answers, this will help you.
First, if you use function "time()" of PHP with + 5 minutes, transform to a datetime string with this function:
date('Y-m-d H:m:s', $row['time_stamp'])
with this, the result is a date formatted: 2022-03-05 12:00:00 (already with 5 minutes included).
Then, download the script from here: http://hilios.github.io/jQuery.countdown/documentation.html After install, use the script of documentation and define a timezone.
The code final code is:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<title>Hello, world!</title>
<script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script type="text/javascript">
var timesZone = moment.tz("<?php echo date('Y-m-d H:i:s',$get['time_zone']); ?>","America/Sao_Paulo");
$("#timer").countdown(timesZone.toDate(), function(event) {
$(this).text(event.strftime('%H:%M:%S'));
});
</script>
</head>
<body>
<center><p><h1>Hello, world!</h1></p></center>
<div class="container mb-2 my-2">
<div class="p-3 shadow-sm">
result of code: <span id="timer" class="countdown">--:--</span>
<?php
$newTime = time()+300;
echo '<br />NOW:'.time().'<br>+5 minutes: '.$newTime.'<br />New time date: '. date('Y-m-d H:s:i',time());
?>
<br />
What i want is: 00:04:59
</div>
</div>
</body>
</html>
I need to add a date and time clock to a website. It should display the date and time in a very specific format, taking up two lines and using an intended timezone of GMT-4; for example:
Sat, Mar 23 2019
10:33:56 PM
This happens to be for a school project, but I have limited knowledge of Javascript. I've tried looking up some examples and have found some interesting stuff, but I'm unable to adapt those examples to generate the output in the desired format.
Please Try This
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var CDate = new Date()
var NewDate=CDate.toDateString();
NewDate = NewDate + " - " + CDate.toLocaleTimeString();
document.getElementById('ct').innerHTML = NewDate;
display_c();
}
<html>
<head> </head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
For Change Date Or Time Format Please Refer this link
Get currentDate by toDateString() method and get current time by toLocaleTimeString and append both in your DOM . And call this every 1000 ms to get updated value .
function callDateTime(){
var currentDate=(new Date()).toDateString();
var currentTime=(new Date()).toLocaleTimeString();
document.getElementById('watch').innerHTML=`${currentDate}-${currentTime}`;
}
setInterval(function(){ callDateTime() }, 1000);
<p id="watch"></p>
You can add an HTML to your the body of your document:
Also, you can add a JavaScript similar to this before </body>:
Code:
function clock(){
window.rt=1000;r=0;
document.getElementById('t-0').textContent=new Date().toLocaleDateString(); // today
var m=setInterval(function(){
if(r>84600){clearInterval(m);}
r++;
document.getElementById('t-2').textContent=new Date().toLocaleTimeString(); // clock
}, window.rt);
}
<!DOCTYPE html>
<html lang="en">
<title>Clock</title>
<body onload="clock();">
<div style="text-align:center;">
📅
<b id="t-0">00/00/0000</b>
⏰
<b id="t-2">00:00:00</b>
</div>
</body>
</html>
I've been trying to make a few javascript based countdowns/timers to place around my web site... an example of this would be...
"I’m a 25-year-old part-time blogger & designer and full-time waitress & bartender!" where the "25" would increase every year to update the age.
another example would be...
"with my soon to be husband (COUNTDOWN TILL WEDDING HERE)" and change "soon to be husband" to "husband"
ive seen a few script round but not quite what i need..
I've been trying to use the Math.floor method which works for the amount of days but i need to figure out how to add years. is there a way to calculate years using math.floor?
sidenote * i am not very familiar with javascript or anything of the sort whatsoever
You can use Javascript to do that:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to My Page!</title>
</head>
<body>
<div id="about-me"></div>
</body>
<script>
function get_message() {
var my_birthday = new Date("2/13/1996"); // update your birthday here
var today = new Date();
var time_diff = Math.abs(today.getTime() - my_birthday.getTime()); // get the difference in milliseconds between today's date and your birthday
var my_age = Math.floor(time_diff / (1000 * 3600 * 24 * 365)); // get your age
var s = document.getElementById('about-me');
var message = "I’m a " + my_age.toString() + "-year-old part-time blogger & designer and full-time waitress & bartender!";
s.innerHTML = message; // update your age
}
window.onload = get_message; // load script only when page is loaded
</script>
</html>
Hope this helps!
I try to format an ISO date string with Intl.DateTimeFormat.
Since it does not accept strings, I have tried to modified the instance's format function.
It returns an error:
RangeError: Invalid time value
var str = '2018-05-30T12:20:51.526Z'
var date = new Date(str)
var dtf = new Intl.DateTimeFormat('en');
var format = dtf.format;
dtf.format = function(str) {
var date = new Date(str);
return format(date);
}
console.log(new Intl.DateTimeFormat('en').format(date)) // 5/30/2018
console.log(dtf.format(str))
Here is a JsBin with the code.
I think you could best use 'moment.js' to format it.
var str = '2018-05-30T12:20:51.526Z'
var date = new Date(str)
console.log(new Intl.DateTimeFormat('en').format(date))
console.log(moment(str).format("MM/DD/YYYY"));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<title>JS Bin</title>
</head>
<body>
</body>
</html>
Import the 'moment' script in your HTML file and you can convert your ISO date to whatever format you want.
I'm building a simple webpage for wedding event. Let's say that I need to show a countdown and I want to get the date to start it from an input form. I've been googling a lot and I've seen some interesting code but it's late and my eyes and mind are very tired. This is my code...
<?php $date = date('2017/05/21'); // this value supossed to be taken from a form.?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="clock"></div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="http://www.testingserver.dev/template/assets/web/assets/jquery/jquery.countdown.min.js"></script>
<script>
var eventdate = new Date("<?php echo $date; ?>"); // I'm trying to use a php variable in jquery.
$('#clock').countdown('eventdate', function(event) {
var $this = $(this).html(event.strftime(''
//+ '<div style="background-color: #ffcc00; width: 25%;"><p>Weeks<br>%w</p></div> '
+ '<span>%D</span> days '
+ '<span>%H</span> hrs '
+ '<span>%M</span> min '
+ '<span>%S</span> sec'));
});
</script>
I suppose this is link to the library website - http://hilios.github.io/jQuery.countdown/
You're passing string 'eventdate' to the countdown() method but it expects to be a valid date. So just remove the apostrophes and you'll get the eventdate variable's value:
$('#clock').countdown(eventdate, function(event) {
// ...
}