I've been having this issue for months and I've finally made some headway. I'm writing an app the sends me a message at specific times, 9 am and 9 pm eastern time. When I ran it locally it worked perfectly but when I deploy it, I get nothing. I was messing around and then I saw this Heroku Logs. My guess is that my app is located on a server that is in a different time zone and when this code below runs. The conditions are never met and nothing gets sent. My question now is, is there a way I can get the current time of and compare regardless of what time zone the server is located?
const sendMessage = require('./sms-api.js');
const send = () =>{
setInterval(()=>{
var x = new Date().toLocaleTimeString();
console.log(x);
if(x === '11:00:10 AM')
{
console.log('match');
return sendMessage('6178032176', 'Good Morning');
}
else if(x === '9:50:20 PM')
{
console.log('match');
sendMessage('6178032176', 'Good Evening');
}
},1000)
}
send();
When working with different timezones, it is better to work in UTC and then offset it according to required timezone.
Get the time in UTC and then offset it according to required timezone.
You can also use dedicated libraries like moment-timezone.
https://momentjs.com/timezone/docs/
Like Suyash said above, your best option is to work entirely in UTC, and only convert when displaying times to users. Rather than dealing with offsets, you can append your dates and times with a 'Z' to indicate they are universal.
The best way I've found to do that is with moment.js and moment-timezone.js. Here is an example of an implementation that will allow you to convert times and dates: https://github.com/aidanjrauscher/browser-timezone-conversions. These libraries also make it very convenient to convert any date or time related user input back from their local time zone to UTC.
thank you for your help. I ended up figuring it out. I used this instead const time = new Date().toLocaleTimeString('en-US', { timeZone: 'America/New_York' });.
Related
I am using Discord.js Node V12 I am currently trying to find out how to say time elapsed in the status to show how long the bot has been playing game or any activity. But i cannot find anyone who has asked or answered any of these questions.
#client.event
async def on_connect():
await client.change_presence(status=discord.Status.dnd,activity = discord.Game(name = "VALORANT"))
I would like to break this answer into a few significant points:
• The sample code provided is from discord.py ( a discontinued python based library to interact with the API ) which is totally out of context of the whole question itself since you're asking it for discord.js
• There is no actual way to find the time elapsed since a particular activity as of now but you may resort to this:
var uptime = client.uptime; // returns uptime in milliseconds
var hours = uptime / 1000 / 60 / 60 // converts it to hours
/*
Then you may apply the following approach to change your status every hour passes
*/
setInterval(() => {
client.user.setActivity(`Valorant since ${hours} hour(s)`);
}, 3600000); // this would show up as Playing Valorant since 1 hour(s) and subsequently would change every hour if your bot isn't being restarted continuously.
I took a look at the discord.js documentation to examine setting activities and found no such information about timestamps. However, there was a section in the ActivityType that led me to the discord developers documentation and it indicates:
Bots are only able to send name, type, and optionally url.
So it doesn't seem as though you will be able to set the start or end timestamps for an activity as a bot.
I am trying to get the current hour of the time which i try in this approach.
var currentTimeHour = dates.ZonedDateTime.now().getHour()
It did return value but it is zero while my time is 3pm. And i notice when the time turn to 4pm, the value return become one.
I did tried getMinute and getDay and it seems fine. Did i did anything wrong and is there anyway to get the hour of the current time?
Thanks.
dates.ZonedDateTime.now().getHour() is correct one to use.
Or you may want to use just dates.ZonedDateTime.now().time.hour
var myNow = dates.ZonedDateTime.now()
console.log('myNow', myNow)
var myHour = dates.ZonedDateTime.now().getHour()
console.log('myNow.getHour()', myHour)
Let's try the above code in JS file, and can see clearly the structure of now() in debug console. As the following screenshot.
First confirm the timezone is correct. IDE may change to a different timezone. This is the screenshot if I change IDE to Indiana timezone.
To confirm/change IDE timezone, use simulator -> User -> GPS/Clock override feature.
I am trying to create a route that functions as the following:
The mobile app will make a request: GET /ballots/today, which should return the ballot for "today" ONLY if the time is between 6:00pm EST - 10:00pm EST.
If the request is made before OR after that period of time, it should not return anything.
I am considering using moment library's isBetween method inside the express route to check if the current time is between 6:00pm and 10:00pm of that specific day.
However, the problem I have trouble understanding is how make sure the server has the correct time at all times (if that should even be a concern) as well as being agnostic to timezones.
If it matters, I am planning on deploying on Heroku.
Moment will always use the server time when running it on express. Most cloud providers have their server time set to UTC. You will have to provide the timezone using Moment Timezone. Here is an example of how to achieve it.
//set the start and end times for today EST
const start = moment.tz("America/New_York").format("YYYY-MM-DD") + " 18:00";
const end = moment.tz("America/New_York").format("YYYY-MM-DD") + " 22:00";
//convert the times to moments so we can do a compare
const startMoment = moment.tz(start, "America/New_York");
const endMoment = moment.tz(end, "America/New_York");
const isBetween = moment.tz("America/New_York").isBetween(startMoment, endMoment);
if (isBetween) {
//return ballot
}
I am looking for a way to obtain a list of timezones in which the current time is a variable (it has to be DST dependant as well).
For example I need to push messages to users for which the local time is 18:45. I can fetch from our database a list of users by timezone. So I plan a scheduled event that would wake up at every 15 minutes, it will need to check in which timezones it is currently 18:45 in order to be able to retrieve the right users.
Our environment is node js.
The way I am thinking about is preferably a web service or some utility that does it all for me including the updates from iana timezones database. But I can handle less convenient ways if there's no such alternative.
Thanks in advance.
Here is one simple way to do it with moment-timezone (I believe it handles things like daylight savings time etc., not 100% sure -- but certainly will do it better than one could do starting from scratch alone.. see their github repo for issues -- its a complex topic):
var moment = require('moment-timezone');
var tm = moment();
var toFind = tm.format('h:mm a');
var userZones = ['America/Los_Angeles', 'America/New_York'];
for (var i=0; i<userZones.length; i++) {
var fmt = tm.tz(userZones[i]).format('h:mm a');
if (fmt === toFind) console.log('matched zone: ' + userZones[i]);
}
hi I'm trying create chat using node.js
I see example in http://chat.nodejs.org/
I have tried it and it works but how can I remove/delete data from server using interval time like in javascript without have to restart node.js/ terminal prompt?....
example:
time:
17:14
17:12
16:13
15:11
14:17
function del(){
if(time<timenow-1000){delete time;}}
setInterval("del()",10000);
I want to delete data less than two hours ago every one hours using interval time...thanks
First off, I would highly recommend against using the setInterval overload you are using that takes an eval string. Instead, always use the version that takes a callback. For example:
setInterval(1000, function () {
// do something
});
Take a look at the source and you will see that messages are stored in the messages array:
https://github.com/ry/node_chat/blob/master/server.js
Your function just needs to inspect this array and remove messages whose timestamp is older than your desired date. For example:
setInterval(1000, function () {
while (messages.length && messages[0].timestamp < someTime) {
messages.shift();
}
});
This will keep removing the oldest message while it is older than someTime, which is a time you will need to specify.