Time between discord message sends not working - javascript

So I am creating an event to listen when there is a message and tell the time from when the last message that was sent. But I can't seem to figure out how to do just that. (I used message.author.lastMessage.createdTimestamp - new Date().getTime()) This does not seem to create a consistent time when I test it out. Any help on what's wrong or anything I need to fix would be appreciated

I recommend you to keep it simple and only use Dates.
// takes a User and returns the milliseconds of difference between now
// and the last message, if there's one.
function lastDiff({ lastMessage }) {
if (lastMessage) return new Date() - lastMessage.createdAt;
}
lastDiff(message.author);
Keep in mind that this can't always print the same number since milliseconds can change between a check and the next one.
Once you have the milliseconds, you can format them as you want.

Related

How to create a time variable that is always updated

I'm sure this has been asked before but I can't seem to find anything that helps, I hope the title make sense, I'm new to javascript and node. In short, I am creating bot for an internal messaging system (like slack). My bot is a reminder bot, so a user can type in the keyword and say "remind me of 'x' in 10 minutes" or "remind me to do 'y' on April 30th at 9:00am" etc.
In my head it made sense to just a have global time variable that is constantly updated like:
if(currentDateTime >= reminderArray[0].notificationTime){
bot.sendMessage(reminderArray[0].message);
reminderArray.shift();
}
push all the reminders on a global queue where they are sorted by reminder time and then execute the bot to send a message when the global time equals the time of the first item in the queue.
I am having a really hard time figuring out how to have a live updated global time variable. I have looked into cron jobs but I'm not sure how to have multiple cron jobs running at the same time.
I have no idea if I'm thinking about it too much or not, it's been like 3 days of banging my head on my keyboard so I might just be in a hole and the answer is probably really simple. Anyways if you can shed any light, offer any advice, or show any examples/tool that I can use I would be so thankful.
Wait, as I was rephrasing the question I realized that code block could work if I put it inside a setInterval(). Something like this:
setInterval(() => {
const time = moment();
if(time >= reminderArray[0].notificationTime){
bot.sendMessage(reminderArray[0].message);
reminderArray.shift();
}
},6000)
what about setTimeout function? You can wrap in setTimeout your function, and your function will be called after N milliseconds, first argument function, second, time in milliseconds, for example:
setTimeout(() => {
console.log('I remind you');
}, 1000)
For your first case, remind me in x minutes, you can use previous, for the second case: remind me to do 'y' on April 30th at 9:00am", you can use something like that:
const reminder = (time) => //argument time in milliseconds which user set
const now = Date.now();
setTimeout(() => {
console.log('I remind you');
}, now + time - now)
For more information about Date.now and setTimeout visit: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Date/now
https://developer.mozilla.org/ru/docs/Web/API/WindowTimers/setTimeout
Hope I could help you!

Get correct epoch time from client even if time on client is wrong

I am building a real time web app that requires epoch time from client. The calculation is involving a timestamp coming from my server and the timestamp from the client. I use the following code to get the epoch timestamp from client using JS:
var milliseconds = Math.floor((new Date).getTime()/1000);
JS is client based, so the value retrieved is based on the date/time the client has. So there is a possibility that the client date/time is misconfigured and the epoch time retrieved is wrong.
Is there a way to make sure that the epoch time from client is the correct one? Or is there a way to correct it if wrong?
Sure, i can use AJAX to get the epoch time from server, but since i use that time inside a countdown function, this means i have to hit the server every second..
[The reason i don't add a second to current time in every loop, is because i have problem when a mobile device sleeps. When the mobile device wakes up it starts counting down from where it were when turned off. It will not consider that the current time is increased. ]
Any advice would be appreciated!
var getClientMillis = function() {
return Date.now();
}
var realStartTime = getServerMillis();
var clientStartTime = getClientMillis();
var getCurrentMillis = function() {
return realStartTime + (getClientMillis() - clientStartTime);
}
You need to implement getServerMillis() yourself.

What is the scope of moment.tz.setDefault() when used in Meteor?

TL;DR What is the scope of moment.tz.setDefault()?
I'm sure my problem here stems from my inexperience with both JavaScript and Meteor but I've been struggling with the problem for several straight days now.
I'm working on an app that must take into account the client's timezone but I'm having significant difficulty in forcing the server code to use the client's timezone. Somewhere along the way--that being from the moment the client presses "Submit" to the moment Meteor inserts--my timezone setting is getting lost and local time (of the server) is being used.
The app flow is like this:
(client) user submits form
(client) validation of data is performed
(server) Meteor method is called
(server) validation of data is performed (same code as earlier)
(server) business logic is applied
(server) insert into DB
I capture the timezone at step 1 and try to pass it along through all the steps but I must be missing something because between 4 and 5 the timezone is (seemingly) lost. The fast is, I'm not seeing why. I've checked this 100 times and tried all manner of different permutations but can't figure out where the gap is (I've used soooo many console.log()s it's crazy.)
So instead of trying to set the timezone at every point Moment() is used (because it defaults to calculating in local time) I discovered moment.tz.setDefault() and tried using that at least once on each .js file in my app. But it didn't work.
Reading this it might sound like I'm not doing enough testing but that is not the case. I have spent 10s of hours on this and I'm just not getting it. I'd love to share the code but I think it's just too long and complicated to properly share so I've done my best to explain the problem.
Good news! You're overcomplicating it :-)
Open up a browser console & type time = new Date(). Notice how it's in the correct timezone? That's because the timezone conversion is happening on the client.
Now, type time.valueOf(). As you probably know, you've got the number of milliseconds since 1-1-1970...but in what timezone?? You guessed it, UTC!
So if all you're doing is saving a number, and the client is fully capable of converting that number into the local timezone, why not save the time in UTC on the server? You'll get an ISODate() in your database (which is a fancy int64). Then, when you retrieve it on the client, you can put it in their local time (they might be traveling!) or any other timezone you chose. If it's a meetup in a certain city, simply grab the timezone of that city & apply it to the field. Hint: THIS is the appropriate time to use moment.js, not before!
Edit for time patterns:
Based on the new info, I imagine you have something that accepts an arrivalTime & then makes sure the time is between an earlyArrival and lateArrival say, 7:00 - 8:30AM. So, save the times as dates
timeToDate = function(time) {
return new Date('1970 1 1 ' + time);
};
earlyArrival = timeToDate('7:30 AM');
arrivalTime = timeToDate('8:00 AM');
lateArrival = timeToDate('8:30 AM');
Then, validate via simple math: earlyArrival < arrivalTime.
OR, if you use simple schema (which you should), a validation pattern might look like this:
departureTime: {
type: Date,
min: timeToDate('5:00 PM'),
max: timeToDate('6:30 PM'),
autoValue: function() {
return timeToDate(this.value);
},
custom: function () {
if (this.value < this.field('arrivalTime').value) {
return "lateAfterEarly";
}
}

updating a Date object on the client side after getting the correct Date from the server side

I have a UI that needs to have the UTC time updated all the time to be shown to the users.
my original code was this:
(function () {
$http.get('api/getdate').success(function (data) {
current = new Date(data.res + new Date().getTimezoneOffset()*60*1000);
updateDateTimer = setInterval(function(){
$http.get('api/getdate').success(function (data) {
current = new Date(data.res + new Date().getTimezoneOffset()*60*1000);
});
}, 30000);
});
})();
data.res has the correct timestamp i need. this way works fine because i can trust my server with the data that is sent back to the UI. then the only data that i need from the user is its offset from UTC and thus i am sure the date that will be displayed will be correct.
my problem is that a call to the server will be made every 30 seconds, and if i want my clock to change even more often then this can get really nasty.
i thought about making the call to the server only one time and then add 1 second with a timer to the Date object created but this is very not accurate and after a few minutes you can see that the clock is not synchronized any more with the real time.
is there any possibly to not make more calls to the server after the first time?
the problem is that i can't make sure the client won't change its local clock. it seems i need to some how deal with the Date object that is being created with the first .get call, but how?
thanks
Could you please clarify the question a bit? If the only thing you're trying to do is find/show the current UTC time, new Date().getTime() returns the millis since January 1, 1970 UTC so that time is already in UTC (2 calls of getTime() occurring simultaneously in New York and Los Angeles will show the same number). Then you have some UTC functions on the Date object which give you the UTC time, like getUTCHours(), getUTCMinutes and getUTCSeconds().

edit javascript on the fly

I was curious how I might go about editing a variable on the fly, since whenever I try nothing happens. Take http://nyan.cat for example. I tried to edit the seconds variable, but nothing happened - why?
i used (in the JS console) seconds = 9001; RET and nothing happens....
That's because in http://nyan.cat/ the seconds variable is being set by the script repeatedly, based on the startTime Date object. In the specific case of http://nyan.cat/, to 'hack' the time, change the startTime.
Example: to increase your seconds by 1234567 seconds:
startTime = new Date(((+startTime/1000)-1234567)*1000);
What JS console are you using?In the firebug?
Here I tested it.
var seconds = 9001;
alert(seconds);

Categories

Resources