Compare date and time in javascript using time in milliseconds since epoch - javascript

Is it a good practice to compare the date and time using the epoch(UTC) time?
I checked it on internet, but did not got example of this. Does this approach has any negative?
if(date_utc1>dateutc2){
//do something
}
Here date_utc1 and date_utc2 are time in epoch

I gathered from the comments that one of the dates is a server-side generated date, but the other is a client-side generated date. Without fully understanding the logic involved here, I´d just like make a short note (sorry don´t have reps for comments) that these two clocks may not fully agree on time (represented in epoch or not).
If possible, a better solution is to only rely on one (the server´s) clock. When the client initially receives data from server, the client persist the server-side timestamp (needs to be part of the response). Down the line, if the client wants to check if the server has more data, the persisted value should be sent back. This way we are sure that the server only returns stuff that has been changed since the last fetch.

You can use Date.now() to get the current time in all recent browsers. You could also use +new Date() to obtain the same number in older browsers if you need to.
Since the data returned from the server is already a number in this milliseconds-since-epoch format, it makes sense to use this information for comparisons, since there is no other calculations or parsing of the data coming from the server that must be done.
I don't believe there are any negatives here.

Related

how to subtract php date from Javascript date

I create project with php Laravel framework and VueJS and I want to get the difference between server time and client time to process some data time out by Javascript in the client browser.
How can i do that?
I need to change the format of one of the dates to be available to manage by other language functions and property.
how to sub (minus) Carbon::now() got from php api Date.Now() in JS.
I do that to get the difference between client clock and the server.
In order to "speak" in dates, the best practice is to work with timestamps.
The server can have its own timezone offset which is why it is best that it will expose any managed dates in UTC.
The client, on the other hand, will need to convert the UTC timestamp to its locale date, which can be done by adding its timezone offset.
Having said that - you will probably want to calculate the data timeout on the server, since the client can be bypassed, thus exposing a timed-out data to potential hackers.
Hope this helps :)

SQL Server Date (not Datetime) to JavaScript Date - one day off

I've tried tons of things to fix this, but the problem continues to vex.
I have a Date field in SQL Server (not Datetime, because time doesn't matter), and a Java API (Spring actually) serves this field to my Ember front-end, where a user can edit the field (using an ember-pikaday input, but that may be immaterial).
The problem is that when I switch to edit mode, the date shows one date before, and if I save, that one date before is what gets saved. If I look at what the API is returning, it looks like the following:
"2015-02-03T05:00:00.000+0000"
I'm still very much learning JavaScript (and Ember), so it looks like there's some local time zone information being used automatically (I'm in EST, which is GMT-5) and that's why it's returning the 5AM time.
I really don't want it to do anything at all with time, but as JavaScript date objects by definition include time info, I'm not sure how to get rid of it. I've tried setting the time to noon so that even with a five-hour difference, it will be the same day, but since the database doesn't save the time, the next time I refresh the page, I'm back to square one.
I've run out of things to Google, which is why I posted here. I'm sure I'm missing something obvious and easy.
EDIT: I tried creating a new variable to get just the date part and using that throughout, but when I go into Edit mode, where my Pikaday input comes into play, it still shows the date before, so I'm suspecting that's the cause of the issue, but I haven't seen hardly anyone else complaining of this.
Here is a similar ember.js question:
Ember.js dates a day early
Also make sure your javascript ISO-8601 date has the timezone. I had a similar issue with web api where the ISO-8601 dates were not sending any timezone info and no Z for UTC and the receiver assumed they were not converted to UTC and made them a day earlier '2012-07-27T18:51:45.53403Z // UTC'. You could use Fiddler or Chrome dev tools to see the format of date you are sending to the server make sure the Z or offset '2012-07-27T11:51:45.53403-07:00 // Local' is there.

Asp-net web api output datetime with the letter T

the data in the DB look like this
2011-09-07 14:43:22.520
But my Web API outputs the data and replace the space with the letter T
2011-09-07T14:43:22.520
I can replace the letter T with a space again in jquery, but can I fix this problem from the Web API (make the web api output the original data?)
I also do not want the miliseconds at the end. How can I get rid of them?
The format of how you see the date in the database is usually irrelevant, because it should be passed into .Net as a DateTime - not as a string. (If you are storing it as a varchar in the database, you have a bigger problem.)
ASP.Net WebAPI is returning the value in format defined by ISO8601 and RFC3339. This is a good thing, as it is a recognized machine-readable format. You probably don't want to change it.
If you really want to change it, you would need to implement a custom JSON.Net JsonConverter, deriving from DateTimeConverterBase. This is discussed here and here.
But instead, you should consider how you are using the actual result in your client application. You mentioned jQuery, so I will assume your consumer is JavaScript. In many browsers, the ISO8601 value that you have is already recognized by the JavaScript Date constructor, so you might be able to just do this:
var dt = new Date("2011-09-07T14:43:22.520");
But this won't work in all browsers. And Date doesn't have a whole lot of flexibility when it comes to formatting. So instead, you might want to consider a library such as moment.js. With that in place, you can do this:
var m = moment("2011-09-07T14:43:22.520");
var s = m.format("YYYY-MM-DD HH:mm:ss"); // output: "2011-09-07 14:43:22"
Please note that the format string here conforms to moment.js, not to .NET. There are differences in case sensitivity. Please refer to the moment.js documentation for details.
One other thing - since the value you provided doesn't have either a Z at the end, nor does it have an offset such as -07:00, then I assume it came from a DateTime whos .Kind value is DateTimeKind.Unspecified. You should be aware that when this gets sent into JavaScript (or anywhere else for that matter), there is no information about what time zone is represented. JavaScript will assume the local time zone of the browser.
If that's not what you had intended, then you need to store UTC values in your database, and make sure they have DateTimeKind.Utc so they get serialized with a Z at the end. JavaScript will normalize this to the browser's time zone, but you will still be talking about the same moment in time.
Alternatively, you could use a DateTimeOffset type - which would serialize with the specific offset. JavaScript will still normalize this to the user's time zone.

Javascript - How do I make getTime() uniform across all computers?

Right now I'm getting a different number on my Desktop than I am on my laptop.
getTime() uses the local time settings. The time settings can be changed in one of two places:
Your OS (such as windows) may manage time; double click it on the taskbar
Your OS relies on the system BIOS, it's one of the reasons that motherboards have a battery installed on the mobo (to keep time and settings in case of system failure), modifications to the time in your BIOS should be reflect in the OS, and consequently in JavaScript
An alternative is to make your own getTime function which pulls the time from one source, such as a server. If you want to minimize network calls, it might be worthwhile to pull this time once and at the same time make a call to getTime(). Then, at some other time, when it's needed, issue a getTime() again, subtract the difference and add it to the server time. Note: if time is important, I advise against this, since a user can easily alter their system clock
Otherwise, if your computers are on the same network, you can use a scheduler and a batch process to sync the times - it won't be perfect, but it'll be close enough
Rather than use the javascript getTime() method, you should rethink your usecase.
If you're looking to timestamp a form submission (e.g. for a comment or form post) you should have the server generate the timestamp when handling the POST
If you want to have a consistent time client-side, consider making an ajax call to a simple web application that returns a timestamp. You could easily write one yourself, or you could use Yahoo's time service
Sync the clocks.
The OS should have an option to use a network time service. There could still be a slight difference, but it should not be more than a second or two, which is good enough for most purposes. How close do you need them to be?
getTime() gets the system time of the computer. However, if you really need to sync, it's best to sync with a web server that you have. Cheers!
You can't, at least not with JavaScript alone. JavaScript uses the system information on the client machine to determine what the time is. Now, if they're in different time zones, you can use the UTC() function to get them in UTC basis (seconds from midnight, Jan 1, 1970), but it's most likely that they just aren't synchronized.
That could be for a variety of reasons. The most likely causes:
The clocks might not be set identically. One (or both) could be wrong.
The clocks could be using different time zones.

Why is there a difference between JavaScript and PHP timestamp

I have created a JavaScript timestamps and also a PHP timestamp. There is about 170 sec difference between them.
1302162686 PHP - time()
1302162517 JavaScript - Math.round(new Date().getTime() / 1000)
Can anyone please tell me why I'm having this issue?
PHP is executed on the server side, and in your example, JavaScript works on the client-side.
Both sides have their own time configuration. For the server, time zone settings etc. will stay the same (unless you change them), but the server has no idea which time zone the current visitor is in. There’s no way for you to control that.
If I change my system clock on my laptop, it will influence client-side JavaScript date/time, but your server timer won’t be affected.
PHP and JavaScript, both look at the system time. Whose system? The one they are running on. The server could be located in another country with different time, hence the difference.
Also, the client's (or less often, server's) clock could be incorrect.
One way, which I often use to counter this problem is like this:
var referenceTime = new Date('<?php echo date("M n, Y"); ?>');
// referenceTime is now the same as server time
PHP looks at the system time, which is the server running it.
JavaScript looks at the client's system, which could be any time.
php uses the time on your server, javascript will use the time on the client (users) machine.
Mathias is correct. Generally this should not happen with that big a difference because modern computers recognize their clocks drift over time and employ protocols such as NTP to keep their clocks in sync.
Nevertheless you should never assume the time at client and server is the same, for two reasons:
Some clients/servers don't have clock adjustments (such as NTP) and their clocks drift away over time
More importantly, many users/admins can be clueless or late in setting their time zone or adjusting daylight savings times, so the time given to you may be accurate to a second but be several hours off.
When comparing/calculating times, I would rely on the server only. You have no control over the client.
If you are concerned about consistency for whatever purpose, I recommend using the server as your time source and do timezone conversions if necessary:
This may be of interest: handling timezone conversion with php

Categories

Resources