I understand how to work countdown timers and date timers to an extent (to a specified date i.e YYYY-MM-DD) but I'm working on a web development college project where I wish for one of my web pages (JSP file) to have a countdown timer with the number of seconds left in the day from when the web application launches.
The web page will also include an Ajax function where the user can click a button and a random motivational message will appear (this particular piece of code I know, but it's just to give you an idea of why I want this countdown timer).
Moment.js is a great library for date math. http://momentjs.com/
Using Moment, you could do a one liner like this.
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
document.write(moment.duration(moment().add(1, 'day').startOf('day').diff(moment())).asSeconds())
</script>
or an easier to understand version:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script>
var now = moment(),
tomorrow = moment().add(1, 'day').startOf('day'),
difference = moment.duration(tomorrow.diff(now))
document.write(difference.asSeconds())
</script>
UPDATED
Simply compare the Date object you get from Date.now() with the date of tomorrow (which you create from the first date object, adding one day);
var actualTime = new Date(Date.now());
var endOfDay = new Date(actualTime.getFullYear(), actualTime.getMonth(), actualTime.getDate() + 1, 0, 0, 0);
var timeRemaining = endOfDay.getTime() - actualTime.getTime();
document.getElementById('timeRemaining').appendChild(document.createTextNode(timeRemaining / 1000 + " seconds or " + timeRemaining / 1000 / 60 / 60 + " hours"));
document.getElementById('dayProgression').value = 1 - (timeRemaining / 1000 / 60 / 60 / 24);
<span id="timeRemaining"></span>
<div>
<span>How much of the day has passed:</span>
<progress id="dayProgression" value="0"></progress>
</div>
Example JSFiddle
Try to use this Javascript code:
var year = 2015 , month = 5 , day = 15;
var date = new Date();
var enddate = new Date(year , month , day);
document.write( date - enddate );
You can edit this code for your site.
Related
I have written some Javascript code that spits out an estimated time frame.
For example, right now, it's giving me: 646 days, 5 hours, 13 minutes
Given that info, if I create a new date in Javascript like:
var d = new Date();
How do I use the info to project the date in the future?
For example, today is June 30, 2018 and 646 days from now is April 6, 2020. So I'd want to calculate that on page load each time, because the projected date is constantly changing.
You have two choices, calculate it in total and add the number (as seen in one of post above), else you can do part by part, meaning day part, time part etc, this way you can write your own mini prototype functions to account for all or say most types of date complexities such as daylight savings etc etc. Just to give a fair idea, start with the date.
To do so use Date.prototype.setDate(), Date.prototype.setHours, Date.prototype.setMinutes()
var projectEndDate = new Date();
projectEndDate.setDate(today.getDate()+646);
// use Date.prototype.setHours(), then
// Date.prototype.setMinutes() and so on
Just add the time to today:
new Date( Date.now() + ((646 * 24 + 5) * 60 + 13) * 60 * 1000)
Or if you want to consider that not every day has 24 hours:
const date = new Date;
date.setDate(date.getDate() + 646);
date.setHours(date.getHours() + 5);
date.setMinutes(date.getMinutes() + 13);
Momentjs Is by far the best library to use for any date calculation.
let endDate = moment().add({
d:646, //days
h: 5, //hours
m: 13
}).format('MMMM D, YYYY')
document.write(endDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
I'm using AngularJS for my application and the date object is $scope.ProductionDate.
From 5:00AM 2017-02-21 (Feb 21st) to 4:59AM 2017-02-22 (Feb 22nd)
I want the ProductionDate value to be 2017-02-21.
P.S. Here Feb 21st is just an example. Daily I want the same value in given timings.
Can I know how to get that?
function Ctrl($scope)
{
$scope.ProductionDate = new Date();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Ctrl">
ProductionDate: {{ProductionDate | date:'yyyy-MM-dd'}}<br/>
</div>
You can subtract minutes and hours in javascript from the Date() object.
function Ctrl($scope)
{
var now = new Date();
now.setHours(now.getHours()-4);
now.setMinutes(now.getMinutes()-59);
$scope.ProductionDate = now;
}
It seems that you want to subtract 5 hours, so that the earlier date is shown.
Here is a SO post which explains how to modify Date object: Adding hours to Javascript Date object? (nevermind the title - you can use the same principles to subtract the hours).
This same operation may also be done by setting the desired timezone.
Just check if date hours are between 0 and 5 or not
function Ctrl($scope)
{
var now = new Date();
if(now.getHours() < 5 && now.getHours() >= 0){
// Subtract one day
now.setDate(now.getDate() - 1);
}
$scope.ProductionDate = now;
}
I have task to make expiry date by adding two months on start date.
I have found this code:
var startDate = Xrm.Page.getAttribute('new_startdate').getValue();
var expiryDate = new Date();
expiryDate.setDate(startDate.getDate()+60); //Add 60 days
var expiryField = Xrm.Page.getAttribute('new_expirydate').setValue(expiryDate);
I can see here how to add 60 days, but I need to add exactly 2 months. Can someone help me about this?
Try to do something like following:
var startDate = Xrm.Page.getAttribute('new_startdate').getValue();
startDate.setMonth(startDate.getMonth() + 2);
Xrm.Page.getAttribute('new_expirydate').setValue(startDate);
Is it possible to define my time to countdown as hours now I have "December 25, 2014 00:01:00" but could I have something like this "14:00" and it runs every day. This is the code I have.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function cdtd() {
var xmas = new Date("December 25, 2014 00:01:00");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
document.write("Christmas is here!");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd()',1000);
}
</script>
</head>
<body>
Days Remaining:
<div id="daysBox"></div>
Hours Remaining:
<div id="hoursBox"></div>
Minutes Remaining:
<div id="minsBox"></div>
Seconds Remaining:
<div id="secsBox"></div>
<script type="text/javascript">cdtd();</script>
</body>
</html>
EDIT
Countdown works fine, but to make it work I have to define time
(mm:dd:yy:hh:mm:ss). My question is can I define time like
this(hh:mm:ss) because the date doesn't matter, only thing that
matters is the time(hh:mm:ss) and when it comes to end countdown
restarts and start counting again to example 14:25:00(hh:mm:ss).
Some working result in this fiddle: http://jsfiddle.net/dehisok/6Wu9a/1/
var now = new Date();
var xmas = new Date(now.getFullYear(),now.getMonth(),now.getDate(),23,1,0);
But there is a bug: if needle time is in past - it crashes :( Unfortunatelly, have no more time to fix.
I have changed document.write to jquery, because d.write isn't supported by jsfiddle.
I hope, it's what you need.
Good luck!
Don't leave parsing date strings to the date constructor. ES5 defines a string format to be supported, but not all browsers support it. Prior to ES5, parsing of date strings was entirely implementation dependent. In this case, you know exactly the date and time you wish to set so use numeric arguments:
> var xmas = new Date(2014, 11, 25);
which will create a Date object for 2014-12-25T00:00:00 in the local time zone based on system settings.
> if (timeDiff <= 0) {
> clearTimeout(timer);
There is no need to clear any timeout, just don't call setTimeout again.
> document.write("Christmas is here!");
If called after the load event, that will clear the entire document. Probably not what you want to do for someone who has been watching the timer up to midnight, then loses the entire page. :-)
> var timer = setTimeout('cdtd()',1000);
Calling setTimeout every 1 second means that the timer will gradually drift and occassionally appear to skip a second. It will also not "tick" consistently if compared to the system clock. Instead, set the delay based on the current milliseconds, e.g.
> var timer = setTimeout('cdtd()', (1020 - now%1000));
so it next runs about 20ms after the next full second. And if the time has expired, just don't call setTimeout.
If you are just looking format the time in hours like hh:mm:ss then you need a small function to padd single digit numbers and then concatenate the values, e.g.
function pad(n){return (n<10? '0' ; '') + n;}
then:
document.getElementById("hoursBox").innerHTML = pad(hours) + ':' + pad(minutes) + ':' +
pad(seconds);
You can work out how to format the date part from there. Note that month:day:year format is very confusing to the vast majority of web users. Far better to use an ISO 8601 format like year-month-day hh:mm:ss
I know there have been a lot of topics like this but I just have problem to which I couldn't find the answer.
My script is:
window.onload = function(){
// 200 seconds countdown
var countdown = 14400;
//current timestamp
var now = Date.parse(new Date());
//ready should be stored in your cookie
if ( !document.cookie )
{
document.cookie = Date.parse(new Date (now + countdown * 1000)); // * 1000 to get ms
}
//every 1000 ms
setInterval(function()
{
var diff = ( document.cookie - Date.parse(new Date()) );
if ( diff > 0 )
{
var message = diff/1000 + " seconds left";
}
else
{
var message = "finished";
}
document.body.innerHTML = message;
},1000);
}
I want to make countdown timer which tells user time how much left depending on his cookie value. So far I managed to calculate difference between two values but I don't know how to make format like, let's say, "dd/mm/yy hh:mm:ss" from difference timestamp (diff). Is it possible at all?
What you want is a function that converts difference in (mili)seconds to something like
5d 4h 3m 2s
If you don't mind having a large number of days for times periods > a few months, then you could use something like this:
function human_time_difference(diff) {
var s = diff % 60; diff = Math.floor(diff / 60);
var min = diff % 60; diff = Math.floor(diff / 60);
var hr = diff % 24; diff = Math.floor(diff / 24);
var days = diff;
return days + 'd ' + hr + 'h ' + min + 'm ' + s + 's';
}
If you have the difference in miliseconds, you'll need to pass the that number divided by 1000. You can also use Math.round to get rid of fractions, but you could just as well leave them on if you want that information displayed.
Getting months and years is a little trickier for a couple of reasons:
The number of days in a month varies.
When you're going from the middle of one month to the middle of the next, the time span doesn't cover any whole months, even if the number of days > 31 (e.g. How many months are there between the 2nd of June and the 30th of July??).
If you really want the number of months between two times, the number of seconds between them is not enough. You have to use calendar logic, which requires passing in the start and end date + time.
PS: When you post a question, avoid irrelevant details. For example, your question has nothing to do with cookies, setInterval, or onload handlers. The only part that you don't know is how to convert (mili)seconds to days, hours, etc. It might be helpful to supply some background on why you're trying to do something, but if it's not essential to understand the basic question, put it at the end so that people don't have to wade through it before getting to the essential part. The same advice applies to your title; make sure it's relevant by excluding irrelevant details (e.g. cookies and counting down).
JavaScript doesn't have any built in date formatting methods like you might expect if you've done any PHP. Instead, you have to build the string manually. However, there are a number of getter methods that will be useful to this end. See 10 ways to format time and date using JavaScript.
Also, just so you know. Date.parse doesn't return the millisecond portion of the time stamp (it rounds down). If you need the milliseconds, you can do either of the following
var d = new Date();
var timestamp_ms = Date.parse(d) + d.getMilliseconds();
or just
var timestamp_ms = +d;
I do not understand why you check the cookie by if ( !document.cookie ) But it doesnot work on my browser so I modified it into if ( document.cookie )
Try toString function and other. Look them up in javascript Date object reference. For example,
var t = new Date;
t.setTime(diff);
var message = t.toTimeString() + " seconds left";
This will print 11:59:58 seconds left on my browser.