Problems calculating time difference Moment.js - javascript

function myFunction() {
moment.locale('pt-BR');
var intervalo = moment();
var periodo = moment("2000", "hmm").format('LT');
var atual = moment().format('LT');
document.getElementById("atual").innerHTML = "Atual: " + atual;
document.getElementById("periodo").innerHTML = "Periodo:" + periodo;
intervalo=periodo.diff(atual).format('LT');
}
In the browser, it displays the message: periodo.diff is not a function
at myFunction.
I want to calculate the difference between the current time at a specified time, timing the remaining time

The format method turns the moment object into a string. Try this:
function myFunction(){
moment.locale('pt-BR');
var periodo = moment("2000", "hmm");
var atual = moment();
var intervalo=periodo.diff(atual, 'years', true);
document.getElementById("atual").innerHTML = "Atual: "+atual.format('LT');
document.getElementById("periodo").innerHTML = "Periodo:"+periodo.format('LT');
document.getElementById("intervalo").innerHTML = "Intervalo:"+intervalo;

Related

How to use an int variable more than once (HTML)?

My program is meant to calculate amount of credits a student has and if they are "University Entrance" (UE) credits.
Once the student enters amount of credits for five subjects I want to calculate the total amount of credits and also the total amount of UE credits, but can't use the assigned amount per standard more than once.
<script type="text/javascript">
function dog(curetn){
var txtJscredit = document.getElementById("txtcredit");
var txtJscredit2 = document.getElementById("txtcredit2");
var txtJscredit3 = document.getElementById("txtcredit3");
var txtJscredit4 = document.getElementById("txtcredit4");
var txtJscredit5 = document.getElementById("txtcredit5");
var txtJscredit9 = document.getElementById("txtcredit9");
if (curetn.includes("credit5")){
txtcredit9.value = ((parseInt(txtJscredit.value)) + (parseInt(txtJscredit2.value)) + (parseInt(txtJscredit3.value))+ (parseInt(txtJscredit4.value))+ (parseInt(txtJscredit5.value)));
}
function myfuntionUE() {
var checkBox = document.getElementById("Uni");
var txtJscreditUE = document.getElementById("txtcredit");
txtcreditUE.value = ((parseInt(txtJscreditUE.value))
}
}
</script>
Try this.
<script type="text/javascript">
var txtJscredit;
var txtJscredit2;
var txtJscredit3;
var txtJscredit4;
var txtJscredit5;
var txtJscredit9;
function dog(curetn){
txtJscredit = parseInt(document.getElementById("txtcredit"));
txtJscredit2 = parseInt(document.getElementById("txtcredit2"));
txtJscredit3 = parseInt(document.getElementById("txtcredit3"));
txtJscredit4 = parseInt(document.getElementById("txtcredit4"));
txtJscredit5 = parseInt(document.getElementById("txtcredit5"));
txtJscredit9 = parseInt(document.getElementById("txtcredit9"));
}
<script type="text/javascript">
var txtJscredit = parseInt(document.getElementById("txtcredit"));
var txtJscredit2 = parseInt(document.getElementById("txtcredit2"));
var txtJscredit3 = parseInt(document.getElementById("txtcredit3"));
var txtJscredit4 = parseInt(document.getElementById("txtcredit4"));
var txtJscredit5 = parseInt(document.getElementById("txtcredit5"));
var txtJscredit9 = parseInt(document.getElementById("txtcredit9"));
function dog(curetn){
if (curetn.includes("credit5")){
txtcredit9.value = (txtJscredit.value) + (parseInt(txtJscredit2.value)) + (parseInt(txtJscredit3.value))+ (parseInt(txtJscredit4.value))+ (parseInt(txtJscredit5.value)));
}
You can use some like that:
var txtJscredit = parseInt(document.getElementById("txtcredit"));
This variable with assume the value of an int.
But take care with this conditions:
https://dorey.github.io/JavaScript-Equality-Table/

How to make each unique timestamp update

I'm working on updating timestamps using Moment JS for a twitter feed clone.
When I add new tweets to the feed the timestamp of the older tweets also updates. I checked dev tools and the timestamp attribute isn't updated, so I'm not sure why it's refreshing.
var tweetMaker = function(tweet) {
var $tweet = $('<div></div>');
// Create HTML Nodes
var name = document.createElement('span');
var nameText = document.createTextNode('#' + tweet.user);
var timeStamp = document.createElement('time');
var timeStampText = document.createTextNode(moment(tweet.created_at).fromNow());
var linebreak = document.createElement('br');
var messageText = document.createTextNode(tweet.message);
// Add Classes
$tweet.addClass('tweet');
$(timeStamp).addClass('timeStamp');
$(timeStamp).attr('data-time', tweet.created_at);
$(name).addClass('name');
$(name).attr('tweetName', tweet.user);
// Build Nodes
name.appendChild(nameText);
timeStamp.appendChild(timeStampText);
$tweet.append(name, timeStamp, linebreak, messageText);
$('#tweetFeed').prepend($tweet)
}
//PROBLEM: All timestamps update with new batch of tweets
var timeUpdate = function(time) {
var timeStamp = $('.timeStamp');
var originalTime = timeStamp.attr('data-time');
console.log(originalTime)
timeStamp.html(moment(originalTime).fromNow());
}
$(document).ready(function() {
initialFeed();
setInterval(timeUpdate, 2000);
$('.name').on('click', filterByName);
$('#originalFeed').on('click', showFeed);
$('#newTweets').on('click', newTweets);
});
});
var timeStamp = $('.timeStamp'); will selecet ALL .timeStamp elements.
You should do something like this
var timeUpdate = function(time) {
var timeStamps = $('.timeStamp');
timeStamps.each(function (i) {
var timeStamp = $(this);
var originalTime = timeStamp.attr('data-time');
console.log(originalTime)
timeStamp.html(moment(originalTime).fromNow());
});
}

How to get the value on a string between 2 identifiers, without replacing the identifiers

I have the following string:
bar
So I can pull the title as a string, but I want to replace the {m{month}m} with {m{August}m} and it needs to be flexible enough so I can also then again replace it with {m{September}m}
I currently have this:
var thetitle = $(this).attr('title');
var newtitle = thetitle.replace("{m{month}m}",months[currentmonth]);
And this replaces fine the 1st time, but then it strips out the entire value and replaces "{m{month}m}" with say "August", so when I need to replace it again I can't target it.
Any help would be appreciated.
G
Try to use
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month
return title.replace('m{' + temp + '}m', month);
}
})();
This works for me. Try
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month;
return title.replace('m{' + temp + '}m','m{'+ month + '}m');
}
})();
var input = $('input');
var a = $('a');
$('button').on('click', function(){
var month = input.val();
var newMonth = changeMonth($(a).attr('title'), month);
$(a).attr('title', newMonth);
console.log($(a).attr('title'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your month here<input type='text'>
<button>Change</button>
var title = "blahblah?foo=1&month={m{August}m}";
var previousmonth = "August";
var previousmonthstr = "{m{" + previousmonth + "}m}";
var currentmonth = "September";
var currentmonthstr = "{m{" + currentmonth + "}m}";
var newtitle = title.replace(previousmonthstr, currentmonthstr);
// Your title is stored in newtitle
View live demo here

Format Moment.js Duration

I am using Moment.js to track the duration of an action in my app. Currently, I have the following code:
var startMoment = null;
var actionClock = null;
function startClock() {
actionClock = setInterval(function(){
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
startMoment = null;
actionClock = null;
}
My problem is, the format of duration is awkward. I want to display the duration as mm:ss.lll. In other words, always show two digits for the minutes, two digits for the seconds, and three digits for the milliseconds. Currently, I see durations printed like 1:2.45. How do I format a duration created with Moment.js? If this is not possible, is there another library I should be using to track a duration and display it?
Thank you!
One way of doing this might be to convert your duration back into a moment (perhaps using milliseconds), and then using the moment's formatting.
moment.utc(span.asMilliseconds()).format('mm:ss.SSS');
var startMoment = null,
$durForm = $('#durationFormatted');
var actionClock = null;
function startClock() {
actionClock = setInterval(function() {
if (startMoment === null) {
startMoment = moment();
$('#duration').text('00:00:00');
$durForm.text('00:00.000');
} else {
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
}
}, 1000);
}
function stopClock() {
clearInterval(actionClock);
var now = moment();
var span = moment.duration(now - startMoment);
$('#duration').text(span.minutes() + ':' + span.seconds() + '.' + span.milliseconds());
$durForm.text(moment(span.asMilliseconds()).format('mm:ss.SSS'));
startMoment = null;
actionClock = null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<div>Duration (original): <span id='duration'></span>
</div>
<div>Formatted moment: <span id='durationFormatted'></span>
</div>
<button onClick='startClock()'>Start Clock</button>
<button onClick='stopClock()'>Stop Clock</button>
I had a similar issue in my project and thankfully, Lodash was already a dependency. I was able to use the _.padStart method to get there.
let yourHours = _.padStart(span.hours().toString(),2,'0');
let yourMinute = _.padStart(span.minutes().toString(),2,'0');
let yourSeconds = _.padStart(span.seconds().toString(),2,'0');

Different line of text each hour

I'm trying to make a site that displays a different line of text depending on the hour (GMT). I have tried using javascript, but I'm very much a beginner! I've managed to piece the following bit of code together but can't seem to get it to work. Any help appreciated!
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11)
{
document.write("<b>Paris</b>");
}
;
});
Javascript has a Date class.
var hour = new Date().getHours();
if(...) {
// do something
}
This code extract
if (hour>10 && hour<11)
can't be working with hours, because time can't be > 10 and < 11 at the same time (hour is an int).
How about:
var now = new Date();
var utcMillis = now.getTime() + now.getTimzoneOffset() * 60000;
var hour = new Date(utcMillis).getHours(); // 0-23
switch(hour) {
case 10: document.write("<b>Paris</b>"); break;
//...
}
Some good info here: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
You could also put your phrases in an array (which you might get from the server):
var phrases = ["Hi!", "blah", "more blah", ...];
... and then you can replace the switch above with:
document.write("<b>" + phrases[hour] + "</b>");
You might want to save yourself some time and use a framework that makes things work pretty much the same way across different browsers. JQuery is my favorite, but there are plenty. Such libraries make it easy to manipulate content in your page, fetch JSON from the server, etc etc.
At first sight:
o.datetime is wrong formatted for JS Date method.
you return an instance of new Date() to get the hour use .getHours()
You can look here to find a way to convert your dateString from o.datetime How can I convert string to datetime with format specification in JavaScript?
Use time.getHours() > 12 instead of time > 12
If you use: getDateFromFormat() from http://www.mattkruse.com/javascript/date/ I think the conversion will be something like E, dd MMM hh:mm:ss +0000
SIMPLE ANSWER:
You can just parse the hour to your callback: (See your JSON here http://json-time.appspot.com/time.json?tz=GMT)
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(o.hour); // See o.hour here
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11) {
document.write("<b>Paris</b>");
}
});
I've created a quick jsfiddle page: http://jsfiddle.net/eBAGS/5/ with a demo that should do what you need. It gets the time from the users PC rather than from a server though, but it could be modified.
HTML
<button onClick="getPhrase()">Show me a phrase for this hour</button>
<div id="placeHolder"></div>
Javascript
function getPhrase() {
h = new Date().getHours(); //Get the current hour
phrase = new Array(); //Create an array of phrases
phrase[1] = 'Hello';
phrase[2] = 'there';
phrase[3] = 'this';
phrase[4] = 'will';
phrase[5] = 'show';
phrase[6] = 'a';
phrase[7] = 'different';
phrase[8] = 'message';
phrase[9] = 'depending';
phrase[10] = 'on';
phrase[11] = 'the';
phrase[12] = 'hour';
phrase[13] = 'of';
phrase[14] = 'day';
phrase[15] = 'that';
phrase[16] = 'you';
phrase[17] = 'look';
phrase[18] = 'at';
phrase[19] = 'it';
phrase[20] = '!';
phrase[21] = 'W';
phrase[22] = 'X';
phrase[23] = 'Y';
phrase[24] = 'Z';
document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}​

Categories