moment().fromNow() depends on user's PC time - javascript

I have an issue with fromNow function in moment js working with user timezones.
It works correctly only when clocks on the user's PC set absolutely correctly.
For example, If I set my clock to -15 minutes from the real time and post a new comment on a website it will show "comment posted in 15 minutes" instead of "comment posted a few seconds ago".
I tried
moment(dateInUTCFromServer).local().fromNow() // in 15 minutes.
and
moment.utc(dateInUTCFromServer).fromNow() // in 15 minutes.
They do now work correctly.
dateInUTCFromServer is a regular timestamp date object from a database. I want to show this date for users in "from now" format. console.log(dateInUTCFromServer) // 2020-01-29 12:25:48
It many cases it gives me "in a second" instead of "a few seconds ago" even when I try to set the correct time on my PC.
In some cases, such issues may be critical. For example, showing deadlines.
Is it possible to use "from now" format ignoring user's PC time settings?

Since you said your dates are in UTC, and in ISO format but do not include a Z or other offset indicator, then the correct code is your second example:
moment.utc(dateInUTCFromServer).fromNow()
The clock on an end user's PC is not something you can control, but it's generally acceptable for one to assume that the end user is synchronizing time. Especially in applications that use third-party authentication (such as a Google or Facebook login) and/or use SSL certificates - both require accurate timestamp validation.
If however you find it critical for the time on the client to be ignored, then you'll need to pass the server's current time to your application.
moment.utc(dateInUTCFromServer).from(currentTimeInUTCFromServer)
Alternatively, if your back end is Node.js, you could just run the original code on the server and pass the string result down to the client.

Related

Getting actual timestemp OS independent

Ok, guys, my problem is simple I need a pop on my website to be shown at certain times and I don't want the user to be able to change time on OS thus tricking the popup and one last thing I would prefer not to query my server for the timestamp. Is there some global API for such thing something like GET currenttimestamp.org?
you could you the site https://worldtimeapi.org/ to get the current time (timestamp or other formats).
You could get it for the current IP
https://worldtimeapi.org/api/ip
Or for a specific timezone.
https://worldtimeapi.org/api/timezone/Europe/London
Check out the documentation for more alternatives: https://worldtimeapi.org/api

Javascript - Increase time dynamically

I have a dashboard page, where I have some time values that come back from the server. These times are in the format: HH:MM:SS (13:05:01, for example). But that value only refresh when then user reloads the page. I would like to do some javascript to keep that value going on... what's the easiest easy to do that? Thanks in advance!
Can you give me a valid reason to spam the servers with requests for time over and over again when the user machine has high probability of having perfectly valid time - is connected to internet and unless user has not messed with it it's correct.
(You might have to offset for zones, not 100% about that)
Downsides of approach to ask server over and over for current time:
You will suffer from latency
You will spam server without valid need
Ability to scale is sinking very fast both by items and users
If you need to check user time matches yours, do a 1 request at the start and then compare times with a bit of offset allowed. If times don't match set the correct time on front from back and display user device time +- whatever the difference was. If they match close enough display user's device time.
Deletes all the negatives. Adds no new negatives.
EDIT upon comment:
Oh, that makes more sense. You can query server on reload but if you expect to reaload a lot (and you need a time to be static after once being set up) you can use localStorage to store it on new browsers or cookies (work for older browsers as well).
For something that is not likely to change I would not query the server again if I don't need to. In case you need / wanna query the server again specifficaly when page loads or reloads you can add this to element on that page onload="myFunction()"
In myFunction handle to call to the back and binding to text of element displaying it.
Personally, I would go about doing it with setInterval, just set it to run the function that updates your time, and set the interval, to 1000 (milliseconds) for it to change every second. You can look Here for more info.

How to correctly interpret DateTime.UTCNow serialized as json, taking time zones into account?

We have server code that uses DateTime.UTCNow and is serialized as
2015-02-17T12:38:58.3220885Z
What is the correct way to interpret these serialized dates client side, taking time zones into account?
I am trying to track down a reported bug where the times appear to be incorrect and 'in the future' - at the client - I have seen no evidence of this however. The idea is for the server and client to simply be working with the same point in time.
Just do
var date = new Date('2015-02-17T12:38:58.3220885Z');
date.toString()
Will give the date according to the local time zone.

Rails: How to get the current user's time zone when using Heroku

I set the time zone of our site on Heroku to Pacific Standard Time (PST) using:
heroku config:add TZ=America/Los_Angeles
Times for users are now always in PST--whether or not they are in the PST time zone.
What's the best way to get the user's actual time zone (i.e. the time zone of where they are physically located)?
I'm guessing that this can be solved using Rails (or Javascript?), as opposed to Heroku.
There are two ways to do this.
Indeed, you can use javascript to fetch their current time/timezone. There is the possibility that the user's computer time is not set correctly, in which case the time zone you display will not be correct.
Because you are using Rails, a recommended way is to get javascript already bundled as a gem, like detect_timezone_rails. This makes it easy to install (because it is all bundled automatically in the asset pipeline.
You can use the IP address to infer their country and time zone. The danger in this case is that a user may be using a proxy. Also, while the IP address generally has city-level resolution, it may be more or less accurate, which may in rare cases give the wrong time zone.
Using the IP address, you can get their approximate city and latitude/longitude. There are many gems that can do this on Ruby Toolbox, eg. geocoder. With the latitude/longitude, you can get the time zone using a gem like timezone.
You can also use one of the above, and allow the user to manually change their time zone on your website (either storing this setting in a database if registered, or as a cookie on their browser). This is useful in case you got the timezone wrong.
There is a couple of ways you could do this depending on how you app is set up. None of which are unique to the Heroku environment.
If your app allows users to sign up then you most probably have a User model, and you may be using the Devise gem for authentication/signup. Add a field to your db (:time_zone) and store the users time zone in this field when they sign up.
>> rails generate migration add_time_zone_to_users time_zone:string
>> rake db:migrate
Rails gives you a handy time_zone_select form helper which gives you a select list with all the Time zones in it which you can display to your user. Add it to the user sign up form and allow the user to set their time zone when signing up.
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/time_zone_select
In your Application Controller you can then do something like this;
before_filter :set_time_zone
def set_time_zone
#current user is a devise method see https://github.com/plataformatec/devise
Time.zone = current_user.time_zone if current_user
end
Then when you display a date in your app call .in_time_zone on the time instance which will display the time in the users time zone.
<%= Time.now.in_time_zone %> or <%= #your_model.created_at.in_time_zone %>
If you don't have user authentication then you could fall back to javascript. To do this you could use the native javascript getTimezoneOffset() on the date object, or even better use the following jsTimezoneDetect plugin:
http://www.pageloom.com/automatic-timezone-detection-with-javascript
Finally you could use a hybrid of both and firstly detect their time zone offset using javascript and then store this value in a rails session/cookie and then use a before_filter to set the Time.zone as above but based on the session time_zone value previously calculated in javascript.
Or you can use this awesome gem
https://github.com/kbaum/browser-timezone-rails

how to get LOCAL TIME, NOT server time?

I use these lines of code to find out the local time in Gujarat - India, regardless server time set correct or not. But i noticed that this is not working. This line produce SERVER TIME, but not LOCAL TIME. It cause problem if server time change accidentally.
What is the exact solution to to get LOCAL TIME in any country in the world?
Dim zoneId As String = "Indian Standard Time"
Dim tzi As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneId)
Dim result As DateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi)
You may want to take a look at Noda, a .net port of Joda an open source project for working with dates. This has been ported by Stack Overflows, Jon Skeet.
A couple Link that might be helpful.
http://www.codeproject.com/Articles/78213/Noda-DateTime-Extensions-for-NET
enter link description here
What you want is the correct local time, regardless of the server defined time.
First of all, the server should be configured with the correct date/time. If you can't trust it, I think you have to rely on a service provided by a third party provider to tell you the correct time.
This other question suggests services you can connect to: Web service - current time zone for a city?
If what you want is the client's time, you have to get it through Javascript and send it to the server side.
Good luck!

Categories

Resources