I am trying to store the time as a difference between 1 jan 2013 and the moment i save it on the database. It is definitely smaller than the standard of making it relative to 1970 ;) both in storage and because i am sending it clientside.
As I am going to do a getRelativeTime() quite a lot, I am looking for simplicity. I might change it from 1 jan 2013 to the date of server launch which is the 1st of a month in 2013 :D
I am keeping client and serverside track in GMT and it is on a nodejs server, the server is unknown. From what I researched, there are some solutions, but many call them incorrect due to this and that :|
To offer a valid answer to your question:
var ms = new Date() - Date.UTC(2013,0,1);
But PLEASE do not do this.
You will end up confusing anyone that uses your system (developers, api clients, database folks, etc.)
You will not be saving as much in terms of bytes as you think. JavaScript Number types are always 64 bits (8 bytes) in memory, see here. How much you might save in the database is very dependent on your database platform, but for example, the MySQL DATETIME type takes 8 bytes, while the TIMESTAMP type takes only 4. The range of a TIMESTAMP is much smaller, reference here and here.
You will probably encounter negative numbers frequently, if your app works with dates before your epoch. They will work, but they could be a source of confusion. If someone isn't aware of your adjusted epoch, they could produce a date that looks valid, but is supposed to mean something different.
You will also throw out any potential for using many great libraries that expect dates to work a certain way. You could convert to and from your custom date to a standard one, but do you really want to constantly wrap and unwrap those values? Probably not. Even libraries like moment.js that use their own types, do so by extending or encapsulating the standard data types. Compatibility is a much higher concern than byte space.
There are a lot of things wrong with JavaScript dates, but the choice of 1/1/1970 as an epoch was a good thing. Just because you can do something, doesn't mean that you should.
Also, consider that disk space is usually the least expensive component to running an application. Even with millions of records, you are likely to save a few dozen megabytes at most. Let's just error on the high side and say you save 200 MB with this clever hack. Amazon's top-tier provisioned IOPS cloud storage is $0.125 per GB per month. Congratulations, you've saved $7.68 over the entire year.
You are trying to normalize the value of epoch time? Epoch time as such gives in positive integer values. ain't it? 1356998400 is the amount of data you want to normalize.
Related
Take the date '2022-04-01' and another date '2022-05-15' for example. When I calculated their deviation in Chrome devtools, what I got is:
The result is 3801600000. But when my friend did the same thing in another device, what he got is:
The result is 3798000000. The difference between 3801600000 and 3798000000 is exactly one hour. What may causes this result? How can I eliminate this difference?
You lack the zone data:
UTC datetime: new Date("2021-01-01T12:00:00Z");
UTC-4 datetime: new Date("2021-01-01T12:00:00-04:00");
The main issue you are experiencing is because your input string is being interpreted as assigned to the local time zone, and you have different time zones on the two machines you've been testing with. One of them has a DST transition between the two dates, and the other does not - which explains your one hour difference.
The examples you show also reveal your possible time zones:
Your machine is showing 8 hours ahead of UTC (UTC+8) for both timestamps. There are several parts of the world that use UTC+8 without DST, including China, Western Australia, Irkutsk Russia, and many others. There are no places on earth that use UTC+8 in conjunction with DST.
Your friend's machine is a different story. The timestamps are showing 2 hours ahead of UTC (UTC+2) on 2022-04-01, and 3 hours ahead of UTC (UTC+3) on 2022-05-15. While many countries use those offsets (such as those that are in Eastern Europe that use EET/EEST), none of those areas have a DST transition between those two dates. See the bottom of this table of DST transitions. All of the +2/+3 areas of the world transitioned in March. I can only conclude that your friend's machine has some non-standard time zone setting, or they are significantly behind on time zone data updates, or both. (Please reply in comments if I am incorrect on this!)
Also, your input string format, 2022-04-01 00:00:00 is not in the standard date time string format defined by the ECMAScript specification. Thus, it is not guaranteed to be parsed consistently by all browsers. Current versions of Chrome, Edge, and Firefox will interpret it as a local date and time, but the current version of Safari will fail with "Invalid Date".
If you want it interpreted as local time correctly in all browsers, you would need to specify it as 2044-04-01T00:00:00.
If you want it interpreted as UTC then specify as 2044-04-01T00:00:00Z.
If you want it interpreted with a specific time zone offset, then append that instead, as in: 2044-04-01T00:00:00+08:00.
If you must parse the string in the original format, then don't do it using the Date object. Either use a library (such as Luxon or date-fns), or parse it yourself with regex and/or string manipulation techniques.
How can I modify a raw Unix timestamp so that it shows that it is 5 hours behind (as an example). I'm looking to do this with a javascript or python. The more lightweight the better. I'm basically looking for how to manually decode a given unix timestamp and change some of its numbers so that it gives me back a unix timestamp showing a different time. It would be even greater if I could automatically adjust it to a users personal time-zone using javascript/python.
Convert to the number of hours you want to offset by to seconds, and then add or subtract it from the Unix timestamp. As far as getting the user's personal time zone, I'm not sure how you would do that without language specific code.
How to choose a time 5 hours numerically smaller
This would be relevant for if, for example, you were testing whether the submission of an exam answer is within 5 hours of the exam's start time.
For this, just subtract 5 * 3600 * 1000 from the Unix timestamp's numerical value.
What you are actually proposing to do is extremely unwise
You seem to be planning to create a Unix timestamp of a different point in time which, when expressed as UTC but with the annotation "UTC" deleted, will match the local time display expected by a user who is 5 hours behind UTC. I can see why you are tempted to do this but it is a very bad idea.
Unix Timestamps do not default to be in UTC, they describe a point in time across all of space simultaneously. If you shift the value of a Unix timestamp, it is no longer a Unix timestamp, just as (mass of car minus 50 kg) is no longer the mass of that car. The value is either the mass of a different car that is 50kg lighter, or an incorrect value for the mass of the original car.
Unix timestamps are unambiguous. Once you know that a variable contains a Unix timestamp, you can stop worrying about any if's, but's or maybe's. It is solid and definite. What you are creating is a horrible thing which looks like a Unix timestamp of an timepoint, but it is not. What variable name are you going to give it to prevent confusion? You might give the physical property a new name, such as the goalieTimeStamp, which is distinguished from Unix timestamps by being displaced by 5 hours.
If a person is 5 hours behind UTC now (in January), that person will likely be a different number of hours behind UTC in summertime. This is a mess.
I think you are doing this so that you can display a local time nicely. Choose a different, better, way to achieve this.
You should use the localisation system in the relevant language to obtain and display the local time, which will depend not only on the location of the user, but also the time of year. This will also allow you to deal with languages etc, if you need to.
And throughout your code you will have a clear distinction between the timepoint of your event (invariant across space) and how a local user will express that time in their timezone, time of year and language.
A good library for this in Javascript is moment.js. It is rather heavyweight, but this is because the task is much more heavyweight that it first seems!
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.
In a form, I'm asking for a start time & end time, which I'll be using in a script later on.
I figured in MongoDB, a time of day is best stored as the # of seconds since midnight (per How can I store time-of-day in MongoDB? As a string? Give arbitrary year/month/day?).
My question is: how can I display a human-readable time in autoform (e.g. 7:30pm) yet still save it as a number in mongodb & have proper client-side validation (make sure time is before 8:00pm)? I figure I could either use a datetime object & subtract the seconds since 1970, or I could parse the time string & do math on the hours, minutes, AM/PM.
Thoughts on methods? & where to put the math hooks in autoform? This seems like something folks a lot smarter than me have probably already figured out!
new Date(<unixTimeStamp>) will get you a javascript Date object which can be easily played with using libraries like moment (https://github.com/moment/moment)
Edit: also, to get the proper timestamp you can do +Date.now(). This jives with mongodb's date type
I am looking for recommendations on displaying times in a web application in a time zone other than the user's current time zone.
We store our dates/times in UTC/GMT in the database, so it is not an issue to format the time for UTC/GMT or the user's current time zone. However, in other situations we need to display the time from the point of view of an arbitrary time zone (i.e. every date/time on this page is in Eastern, regardless of whether or not the user is in West Coast, Central, Eastern, etc.).
In the past we have stored offsets or time zone info, then done the calculations in server code in .Net or else we have done some client-side manipulations in javascript that I would prefer to avoid, since it all becomes very dependent on javascript and the user's browser. I'd like to know the best way to do this in a more client-side/MVC type application.
Here is an example:
Date stored in db: 1302790667 (Thu, 14 Apr 2011 14:17:47 GMT)
Converted date displayed for a client in Central time zone: Thu Apr 14 09:17:47 2011
Date I actually want to display, always in Eastern time zone: Thu Apr 14 10:17:47 2011
In the above example, it's easy to get the time in UTC (#1) or the user's current time zone (#2) but it is more difficult to get #3. My options seem to be:
Store offsets or time zones in the db and do calculations on the client - this is what we've done in the past with .Net but it seems even messier in client side code is the path we are currently trying to avoid.
Do the conversion on the server and send down a full date for display to the client - client receives a string ("Thu Apr 14 10:17:47 2011"). This works but it's not very flexible.
Do the conversion on the server, break it into parts and send those down to the client, then put them back together. ("{DayOfWeek:Thu, Month:Apr, Day:14, Hour:10, Minute:17}"). This gives us the correct data and gives us more flexibility in formatting the date but it feels a little wrong for this scenario.
Any other options ideas? How do others handle similar situations? Thanks.
Our results:
I tried out a few libraries like Datejs, MS Ajax, etc. and I was never very happy with them. Datejs didn't work at all in a few of my test cases, is not actively maintained, and seemed to focus a lot on syntactic sugar that we don't need (date.today().first().thursday(), etc.)
We do use jQuery for some basic date/time parsing.
I came across a lot of "roll-your-own" client-side date conversion "hacks", most of which only addressed the conversion to UTC, started off working fine, and then eventually fell apart on some edge case. This one was the 90% solution for a lot of standard UTC conversion but didn't solve our "arbitrary timezone" issue.
Between the code complexity the conversion routines added and the bugs they seemed to cause, we decided to avoid client side date processing most of the time. We do the date conversions on the server with our existing date handling routines and pass the formatted dates or info down as properties to be used by the view. If we need a separate date, we just add another property. There are usually only a few properties that we need at a time (i.e. EventDateUTC, EventDateLocal, EventDateAlwaysAustralia, and EventDayOfWeek).
I offer the suggestion that you look into the Datejs library. It offers a bunch of extensions to basic JavaScript date manipulation, including a "setTimezone()" method and flexible ways to convert a date into a formatted string for display.
I usually hesitate to suggest libraries when their use is not explicitly allowed for in questions, but Datejs isn't very large and it's pretty solid (even though it's called an "alpha" release). If you'd prefer not to rely on something like that, you might want to look at it anyway just to see the basics of how its extensions were implemented.