What is the best practice for saving some time informations in JS?
In my case I want to save the datetime as a user account is created. 36h after creating the account I want to show a message to the user.
Right now I'm saving a timestamp with new Date().getTime();. But maybe it is possible to calculate for some events just with new Date()?
This is how I do it, but it feels not very elegant - especially for complex calculations.
var currentTime = new Date().getTime();
if ( (timeRegistrated + 1000 * 60 * 60 * 36 - currentTime) >= 0 ) {
console.log('36h are over...');
}
I think I have to use some library for complex calculations (like current age of user or how many months between two dates)... But still the basic question: Which type of date-data should be used for the DB?
Moment.js has a fromNow function. It's way easier.
http://momentjs.com/
moment("20111031", "YYYYMMDD").fromNow();
Related
I have:
# Python
import datetime, time
py_utc_now = int(time.mktime(datetime.datetime.utcnow().timetuple())) # 1597879534
# Javascript
var js_utc_now = Math.round(new Date().getTime() / 1000); # 1597861534
py_utc_now - js_utc_now
>>> 18000 # seconds
18000 / 60
>>> 300.0 # minutes
I was always taught that UTC time was always based on GMT in London, no matter what part of the world you are in. And I'm currently in the Chicago area (-5 GMT), so this makes no sense either way.
Why are my values 5 hours apart? And how can I get the exact time for each, regardless of where I am in the world?
Your Python code is taking a time that is already UTC, and then passing it to mktime, which expects local time values. This effectively doubles the timezone offset, resulting in the error you're seeing.
To get the correct UTC timestamp in Python, you can use a much simpler expression:
int(time.time())
You need to use Date.UTC() to retrieve the UTC date in JS.
Both datetime and new Date() derive their values from the settings of the machine they are running on. It does not matter where in the world you are.
In Python:
py_utc_now = datetime.now(timezone.utc)
In JS I suggest you use a third-party library called dayjs. It's super small but it gives you a lot of flexibility when working with dates and time.
Or you can use the getUTCDate() method.
var currTime = new Date();
var js_utc_now = currTime.getUTCDate();
I have this code here:
var date = a.created_at_timestamp.substring(0,10)
var time = a.created_at_timestamp.substring(11,19)
And both these values return strings with these values:
date = 2020-05-19 //
Time = 17:00:08
I need to subtract 3 hours since it's coming in GMT time and I'm on GMT-3. Therefore, I thought about adding them together, subtracting three hours, and putting them apart again. Something like:
Orig Date: 20/05/19 //
Orig Time: 20:15:19
Time + Date: 20/05/19 20:15 //
Time + Date - 3h: 20/05/19 17:15
New Date: 20/05/19 00:00 //
New Time: 17:15:19
I tried converting it to milliseconds as suggested in other post here, doing with formulas, where a function would trigger formulas adding both cells, which I was able to do, but couldn't tear them apart together. In addition, if possible, I'd like to do it inside the script.
Can someone help me with that?
I'm new at this and I'm somewhat used to VBA. Tried some things from VBA, but they don't really apply here.
Instead of having separate strings for date and time, it'd likely be easier to just create a new Date object with both combined.
var dateTime = new Date(a.created_at_timestamp.substring(0,19));
You can then subtract 3 hours by doing:
var timeOffset = 3 * 60 * 60 * 1000; // 3hrs of millis
var offsetDate = new Date(dateTime.getTime() - timeOffset);
How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/
Rails provides a timestamp like follows: 2012-12-21T01:09:32Z
How can I use JavaScript to determine how many days old the timestamp is?
Thanks
You can use new Date('2012-12-21T01:09:32Z') to turn the string into a Date object. Then use simple arithmetic:
var dateStr = '2012-12-21T01:09:32Z',
daysAgo = (new Date() - new Date(dateStr)) / 86400 / 1000;
if (daysAgo > 7) {
// more than 7 days ago
}
You may want to use Math.floor(daysAgo) or Math.ceil(daysAgo) to round the results down or up, depending on your situation.
Does anyone have any solid examples of how to implement a jQuery or javascript based age checker? I'm looking to send someone to a page where they need to enter in the Day, Month and Year at least once a day when they hit any page on the site. Once they validate as 18 then they would not be pestered again until the next day if they return.
Any ideas?
A cookie-based solution does seem a logical fit since you can programmatically modify them from JavaScript and you can set their expiry. Calculating the date in pure JavaScript can be done as such:
var millisPerYear = 1000 * 60 * 60 * 24 * 365;
var birthdate = new Date(year, month, day); // from user input.
var age = ((new Date().getTime()) - birthdate.getTime()) / millisPerYear;
// Now set the "age" cookie.
All that is left is for your server-side response handlers to return content conditionally based on the value of the "age" cookie from the request agent.
There seem to be a number of existing resources on the web for implementing similar functionality. All of them create a cookie with the birth day selector which held by the user and can be set to expire a day later. Obviously this can be a problem if your users don't have cookies enabled. Below are a couple of examples.
http://www.webdesignforums.net/php-67/age_verification_script-30188/index2.html
http://www.techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/
There is a wonderful Date library for JavaScript called DateJS. It makes date operations extremely simple.
Your first step is, of course, to parse the date that is provided. DateJS provides a lot of parsing functionalities, such as:
Date.parse("Mar 3 2010");
Date.parse('March 20th 1973');
Date.parse("03 12 2010");
Once you have parsed the date, you can compare it to the date 18 years ago. This is also easy with DateJS
var userBDay = Date.parse("Mar 3 1970");
var eighteenYearsAgo = (18).years().ago();
var is18 = (userBDay >= eighteenYearsAgo);
You are of course assuming the user is honest. Not to mention JS can be disabled, or modified client side. But that is an entirely different discussion.
EDIT: Had forgotten about your mention of only doing verification once a day. This would require either:
Cookie (client side)
HTML5 LocalStorage (client side)
Session, where last verification can be provided either at the time of the page rendering or through an AJAX request. (server side w/ client side component)