Parse Clouod Code Check If Date Is Today - javascript

In my app i want a feature where the user can update their status but i want them to only be able to update it once every 24 hours. Basically i want to take the updatedAt field from parse and check if the change was today in Cloud Code.
I am not very familiar with javascript but her's what i've tried:
https://www.parse.com/questions/compare-date-and-createdat-to-figure-out-the-difference-in-days
How to compare 2 Date fields in Parse Cloud?
I couldn't get to a solution that would basically tell me (beforeSave) if the date is today and allow the user to save/update the field if it isn't.
An example of what i want is WhatsApp that only allowed changing the last seen status on/off once every 24 hours. Also Viber has this feature.
Thanks.

Parse.com supports moment.js
var updatedAt = ... ; // Get updatedAt value of your object
var now = moment();
if (now.diff(updatedAt, 'hours') >= 24) {
// Last update was more than 24 hours ago
}

Related

How to store birthdays in a database with timezone support?

I am using JavaScript and a PostgreSQL database, I would like to store birthdays and notify users at 12pm in their own timezone, currently I am converting dates from their timezone to my local server time and check every hour to see if a date and time matches
import { parseFromTimeZone } from "date-fns-timezone";
const userInput = "08-11" // day/month
const timeZone = "Europe/Amsterdam"
const date = parseFromTimeZone(`2000-${userInput} 00:00:00`, { timeZone });
// This is what I store in my database
const dateToStore = date.toISOString().slice("2000:".length).split(":")[0];
// This is what I run every hour
await Birthday.find({
where: {
date: new Date().toISOString().slice("year:".length).split(":")[0],
},
});
The problem is that this solution is not very dynamic because if I migrate my server it breaks, my questions are:
How can I store the birthdays? Assume users provide the month, day and time zone
In what interval can / should I check to see if a birthday message should be sent? (00:00) in the user's time zone and specified date
What would that check look like?
I have date-fns available but I do not mind using other libraries
I'd recommend a solution with a account table containing three fields:
birthday, which is of Postgres type date.
timezone, of Postgres type text. Here you'd store something like Europe/Amsterdam, with the important part is that it's something Postgres and your date libraries can all recognize as a time zone.
last_birthday_wish_sent_at of type timestamptz (shorthand for timestamp with time zone, which stores everything internally as UTC).
I've decoupled the birthday date from its timezone because remember that a user's birthday is always the same day anywhere in the world, even if they move around. So if my birthday is August 11th in Amsterdam, it's still August 11th if I move to San Francisco. Storing these components separately would allow you to reconfigure their timezone if they move.
I'd run a cron on the 0th minute of each hour that ran logic something like this (pseudocode, sorry):
for timezone in all timezones:
if > 12 PM in timezone:
for account in accounts in timezone:
if birthday <= today AND (last_birthday_wish_sent_at IS NULL OR last_birthday_wish_sent_at < now() - '1 year):
send birthday wish
set last_birthday_wish_sent_at = now()
The purpose of last_birthday_wish_sent_at is so that you can write an algorithm that's a bit dumber and more resilient (i.e. birthday wishes still get sent even if the cron fails one hour), but still make sure to never double-send a birthday wish for any given year.
It might also be safer to model this as a separate table where you track every birthday wish you've ever sent and the user and year you sent it for. This eliminates any potential for time bugs across year boundaries.
You'd want to model the account selection and filtering in the pseudocode above as SQL so that you're not returning result sets larger than necessary. Something like:
SELECT *
FROM account
WHERE timezone IN ('Europe/Amsterdam', ...)
-- note: actual date comparison a little more complicated than this
-- because you should make sure to compare the month and day components
-- only (probably with the `EXTRACT` function)
AND birthday <= NOW()
AND (
last_birthday_wish_sent IS NULL
OR last_birthday_wish_sent < NOW() - '1 year'::interval
);
And make sure there's appropriate indexes on timezone, birthday, and last_birthday_wish_sent.
You could also tighten up the logic around time zone checks: it's always turning 12 PM somewhere, but it's perfectly predictable as to where that's happening so it's not necessary to check every time zone every time. You could also potentially push this into Postgres and get the whole selection logic packaged up into a single query.

How do I convert firebase.database.ServerValue.TIMESTAMP to its corresponding date or time now?

Here is my code, where I push a newsObj to the realtime database
addNewsObj(newsObj:News) {
this.newsListRef.push(newsObj).then((snap) => {
const key = snap.key;
console.log(key);
this.newsListRef.update(key, {news_timestamp_post_created: firebase.database.ServerValue.TIMESTAMP});
});
}
The outcome I want would be converting the long value I get from the db, something like this
news_timestamp_post_created:
1535716975480
To 59 mins ago or when it exceeds 24hrs, it displays it by days then months as time goes on. I wouldn't want something like 3000mins ago or 120days ago to be displayed on my app.
My problem here is that I dont know how to convert this 1535716975480 to readable terms
Any small tip would be a great help. Thank you!
EDIT:
I have tried doing this
let elapsed = news.news_timestamp_post_created;//1535716975480
console.log(new Date(elapsed));
which displayed 'Invalid date'
According to this SO link, the server timestamp is
"The doc says:
A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers"
I found out that,

Age Check and jquery

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)

Java Script: How to ammend a datetime variable to set a specific time?

I need to take a datetime values from an MSSQL based app which is read into the script as 22/12/2010 3:56pm and adjsut the time component toa set time.
I've used what I know of javascript and what I can find in google searches to try and progress this but to no avail.
Premis: I need to read the date time value and set the time portion of the date to 8am, 1pm or 4pm dependent on another field.
The conditional logic portion of the script is fine the date functions aren't so fine.
Current code I'm currently using:
if(fldPriority.Value=='2')
{
var ResDate = new Date(fldTargetResolutionTime.Value);
var newdate = new Date(ResDate.getYear(),ResDate.GetMonth(),ResDate.GetDay(),16,0,0,0);
objReturn = newdate
}
Problem:
The date reads in originally in gmt format 22/12/2010 3:56pm but then gets changes to utc format and the date changes significantly to Wed Oct 12 15:56:00 UTC+12 2011
Any help would be greatly appreciated.
Make a copy of the Date and set the time using UTCHours.
The return value will be the correct Date and time,
but you if need to convert it to a string the string will be local time unless you call newDate.toUTCString();
(or objReturn.toUTCString())
var newdate=new Date(ResDate);
newDate.setUTCHours(16,0,0,0);
objReturn=newDate;

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources