Use moment and moment-timezone to calculate seconds remaining till an event - javascript

I am creating a countdown for an event and the server gives me the number of seconds left till this event. It works fine in the same time zone America/New_York but I am not sure how to achieve this for a different time zone. I guess I have to add/subtract a number of seconds based on user't time zone. I am taking into account that the number of seconds returned by the server will always be in EST. Can someone advise?
So far I have this but I'm getting an error:
let serverZoneTime = new moment().tz.zone("America/New_York").offset(now);
let currentZoneTime = moment.tz.guess().offset(now);
console.log((EstTzOffset - currentTz));

First of all, if this is an event at 6pm on a certain day I would get the exact timestamp or UTC time for that event start time. Below I'm using a fake timestamp.
This is important because the people viewing your event could change from EST to DST between "now" (which you are using above) and 6pm on the event day.
It sounds like you already have the countdown working but it is just the timezone issues you are dealing with so I'll skip the countdown logic.
const moment = require('moment-timezone');
// Get User's Timezone
const userTimezone = moment.tz.guess(); // this has to be on the client not server
const serverTimezone = "America/New_York";
// Get the exact timestamp of the event date apply the server timezone to it.
const serverEventTime = moment(34534534534, 'x').tz(serverTimezone);
// Take the server time and convert it to the users time
const userEventTime = serverEventTime.clone().tz(userTimezone);
// From here you can format the time however you want
const formattedUserEventTime = userEventTime.format('YYYY-MM-DD HH:mm:ss');
// Or format to a timestamp
const userEventTimestamp = userEventTime.format('x');
For a countdown you'll want the time now as well, which follows the same logic as above:
const serverTimeNow = moment().tz(serverTimezone);
const userTimeNow = serverTimeNow.clone().tz(userTimezone);
// Get timestamp so we can do easier math with the time
const userNowTimestamp = userTimeNow.format('x');
Now all we have to do is subtract now time from the event time to get the difference and repeat every second using a setInterval() perhaps.
const millisecondsToEvent = userEventTimestamp - userNowtimestamp;
const secondsToEvent = millisecondsToEvent / 1000;
Hopefully that's useful to someone (just realized that this was two years old).

Related

Javascript - Setting Custom Time in Unix Timestamp

I'm working on a program that takes input from a user for a time. The program will take the information and automatically generate a Unix Timestamp using the current date as the date in the timestamp.
For example:
Daniel wants to generate a Unix Timestamp for 8:30 AM on Christmas
Day. He runs a command /unix 8:30, and the console prints out
1640421000.
What's the best way to achieve this? I understand how to generate a Unix Timestamp, but how do I edit just the time to the user input. Any help would be greatly appreciated.
You can create a Date for the current date, set the time as required, then generate a time value in seconds.
If the user will always enter H:mm and you don't need to validate the input, then the following will do:
let time = '8:30';
let tv = new Date().setHours(...(time.split(/\D/)), 0) / 1000 | 0;
// Check value
console.log(new Date(tv * 1000).toString());
However, the input should be validated (e.g. hours 0-23, minutes 0-59).
I just went with the following:
const time = interaction.options.getString('time');
const date = new Date().toISOString().slice(0, 10);
console.log(Math.round(new Date(`${date} ${time}:00`).getTime()/1000));
Seems to work for me.

Attempting to get momentjs to calculate difference in times

I am trying to setup a interval to run every morning at 0730. I am trying to use momentjs to accomplish this.
e.g:
current time - 0730 = how long to wait until it is time to run the function.
For some reason no matter how I manipulate the moment it seems to come back with some wonky math. For example it is currently 0616 in the morning and when I attempted to get this to do the math it came back with a 6hr difference not just over an hour.
var endOfShift = moment('0730', 'HHmm').format(),
now = moment().utcOffset(-8).format(),
diff = moment(now).local() - moment(endOfShift).local();
console.log(endOfShift); // => 2019-12-20T07:30:00+00:00
console.log(now); // => 2019-12-20T06:11:38-08:00
console.log(diff); // => 24098000 milliseconds = 6.6938888889hrs
I have tried removing the utcOffset from now which then the out put for the time/date incorrect. I have tried adding utcOffset to the endOfShift variable. No matter how I mess with the utc it still seems to = around 6hrs when it should be about 1ish. I have tried just removing the utcOffset from everything and just let it do its thing and it still gets the math wrong.
I have also tried moment's diff method w/ similar results.
What am I missing?
-Adam
I think you can achieve this with something like this
const now = moment();
let targetTime = moment('07:30', 'hh:mm'); // could be in past or in future
if (targetTime.isBefore(now)) {
targetTime = targetTime.add(1, 'day'); // add one day if waiting for tomorrows time
}
const diff = targetTime.diff(now);
console.log(diff);
const otherDiff = targetTime - now;
console.log(otherDiff);
The values for diff and otherDiff should be equal so it's up to you which one you prefer.

How to get time range of todays date with timezone in javascript and use it in mongo query

I want to run a query in mongo which will get data till 7:00 am, then 7 am to 11 am and then 12 pm to 4 pm of particular that day only. Now these time are stored in different timezone. So I want to know how get data from mongo.
I tried using momentJs to get the the time range but not able to get correct timezone.
var dayStart = moment().zone(timezone).startOf('day');
var now = moment().zone(timezone);
var duration = moment.duration(now - dayEnd);
and my mongo query is
db.CollectionName.find({"created_at": {
'$gte': dayStart,
'$lt': now
}});
I want the three result seperately that is till 7am, 7am-11am & 12pm-4pm. Any help please.
I would still advise against using moment().zone() - at the very least use moment().utcOffset() as it more clearly communicates the approach of the function. However, since you are using .zone() now I will share an example to get you started.
We assume the following:
when a record is saved to your database, the created_at value defaults to UTC
you are the only user of concern
you are located in the Kolkata timezone and when you say 7am, you expect it to be relative to that location on earth
Using the zone feature, you would then need to a value of -330 to translate from UTC to Kolkata. (Since Kolkata is UTC+5:30, we must convert to minutes and then subtract that value 5 * 60 + 30 = 330.)
Given all of that, your values will be as follows:
var dayStart = moment().utc().zone(-330).startOf('day');
var now = moment().utc().zone(-330);
var duration = moment.duration(now.diff(dayStart)).as('minutes');
you had a few typos in your example: dayEnd was an undefined variable, I assumed you meant to use dayStart. also, duration needs to use diff and an argument to format the output, I have used minutes for this example.
You can test further and play around with this example:
https://jsfiddle.net/dusthaines/48wubezy/5/

moments JS - correct way to compare local time

I'm trying to use moment.js to compare a date stored in the database (which is set to Europe/London timezone) against the current users time, taking into account their timezone.
I get a date string returned from the database and want to use the fromNow() function, as follows:
console.log(dbDate);
console.log(moment().format());
console.log(moment(dbDate).fromNow());
// DB stored time (Europe/London)
// 2017-09-26 06:56:26
// Current user time (timezone is Pacific Time / Los Angeles)
// 2017-09-25T23:59:03-07:00
// String output by fromNow() function, which should reflect the timezone difference but doesn't
// in 7 hours
I want the fromNow() string to take account the timezone difference and this should always be a time "ago" as opposed to in the future.
I'm probably missing something quite obvious with the library, so apologies in advance if this is very simple.
// get the current time so we know which offset to take
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now);
var MY_DATE = moment(dbDate);
// calculate the difference in hours
console.log((NewYork_tz_offset - MY_DATE) / 60);
Does this help your cause?
You have to use moment timezone, you can parse dbDate specifying "Europe/London" timezone using moment.tz:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Then you can use moment diff and fromNow.
Here a live example:
var dbDate = "2017-09-26 06:56:26";
var now = moment();
var momDbDate = moment.tz(dbDate, "Europe/London");
var pacificTime = moment("2017-09-25T23:59:03-07:00");
console.log(dbDate);
console.log(moment().format());
console.log(momDbDate.fromNow());
console.log(momDbDate.diff(now, 'hours'));
console.log(momDbDate.diff(pacificTime, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>

jQuery time difference of utc offSets

I want to find time difference between user's time and server side time. Like what time is user having on his system and what's the value coming from database. I have got it approximately.
But now my problem is what if user is from difference time zone rather then the value is coming from database? So now I want to find the exact difference by managing their time zones. Here I am putting my sample code and the values I am getting with their formats.
var studentSessionStartTimeDate = that._sessionData.studentSession.dtStart; //date with time from db
var splitTimeDate = studentSessionStartTimeDate.split(' ');
var oldDate = splitTimeDate[0]; // split date different
var dateold = new Date(oldDate).getTime(); //convert date into milliseconds
var time=that._sessionData.studentSession.start; // User's exact start time from db
var convertedTime=(Number(time.split(':')[0])*60+Number(time.split(':')[1]))*1000; // converted time in milliseconds
var sessionStartTime = dateold+convertedTime; // db time and date value in milliseconds
var systemTime = new Date().getTime(); // user's system time value in milliseconds
var timeDiff = sessionStartTime - systemTime; // now i want this time diff to be exact but it is not calculating the zone difference
Now if someone want I can get utc Offset from db also, but how can I get difference?
you could get browser time zone with following code:
new Date().getTimezoneOffset();

Categories