Node.js | check days left on account - node.js

I want to verify Date is valid for subscription.
Date is in UTC format.
when user creates an account i set the expiration date to be the date in 30 days.
Before each action, i want to verify the expiration date of his account.
To get the days left for user i do
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
Now i want to check that if daysLeft is 0, then do some action alerting the user.
My problem is, that is if expiration was a year ago, then days left will not be below 0 as i expected, it will be 300+.
how can i enforce it?

With this you just get the difference between those dates:
let oneDay = 24*60*60*1000;
let daysLeft = (userSubscription.expired - new Date())/(oneDay))
So the result after one year would be 365 - 30 = 335
But you need to check if userSubscription.expired is higher than new Date()
Use something from here: Compare two dates

Related

NodeJS: Check if day is sunday - TZ offset problem

I would like to restrict some actions if date is on sunday - e.g. do not allow create item on Sunday.
I use:
public isSunday(date: Date): boolean {
return date.getDay() === 0;
}
My problem is that my UTC offset is UTC+2.
Server and database runs on UTC TZ to prevent unwanted date and time shifts.
When I send datetime from frontend I use date.toISOString(), so my local datetime
2022-05-16 00:00:00 is converted to string 2022-05-15T22:00:00:000Z
When I check this date on the backend side, this date IS sunday, but in the UTC zone, not my local zone.
String value is converted to Date at the backend using following
new Date(input);
Edit: Value 2022-05-16T01:41:00+02:00 (sending value with utc offset info) does not work either
To my understanding, you need the local (UTC+2) zone on the back-end for only Sunday checks.
You can simply subtract 2 hours equal to milliseconds from the date received on the backend before the Sunday checks.
// ... get date here
date -= (2 * 60 * 60 * 1000); // subtract 2 hours
I don't think this is a good practice as your frontend may change its timezone but you can try this.
const date = new Date("2022-05-16 00:00:00")
const corrected_date = new Date(date.valueOf() - 7200000) //subtract milliseconds as needed, in this case 2*60*60*1000
console.log(corrected_date.getDay())
If possible, then you should maybe try sending the UTC offset as a seperate parameter to the backend and calculate the correct value to be subtracted for it to work dynamically.

Difference between using `Period.Between` and substracting two local dates

Why is the result for the periodBetween.Days and substracted.Days different?
I can see that a periodBetween.Months is 0 and substracted.Months is 2 and I can see how are these two results different, but I don't know why :).
using NodaTime;
void Main()
{
var firstDate = new LocalDate(2020, 8, 1);
var secondDate = new LocalDate(2020, 10, 30);
var periodBetween = Period.Between(firstDate, secondDate, PeriodUnits.Days);
var subtracted = secondDate - firstDate;
Console.WriteLine(periodBetween.Days);
Console.WriteLine(subtracted.Days);
}
Your periodBetween calculation is saying "What's the period between these two dates, using only days?"
Your subtracted calculation is equivalent to calling Period.Between either without specifying any units, or specifying PeriodUnits.Days | PeriodUnits.Months | PeriodUnits.Years - in other words, "What's the period between these two dates, using days, months and years?"
A period has independent values for years, months, days, hours, minutes etc - if you compute a value using years/months/days that's not equivalent to computing a value using just days.
A period of "90 days" is not the same as a period of "2 months and 29 days". In some calculations they'll give the same answer, but not always. For example, if you add "90 days" to January 1st 2020, you'll get March 31st 2020... but if you add "2 months and 29 days" to January 1st 2020, you'll get March 30th 2020.

Stripe: Prorated amount using billing_cycle_anchor

I am using billing_cycle_anchor when creating a subscription. I have a requirement where I need to charge from the day of payment to last of the month. And then from 1st of every month.
I am using code shown below:
var date = new Date();
var lastDay = Date.UTC(date.getFullYear(), date.getMonth() + 1, 0);
var monthLastDay = Math.floor(lastDay/1000);
let subscription = {
metadata: metadata,
billing_cycle_anchor: monthLastDay
};
Using above below is what is happening:
Prorated amount is charged from May 16 to May 31st
Subscription is created from May 31 – Jun 30.
But I want subscription to be created from June 1.
EDIT:
Right now time which is being calculated is:
1527724800
which is equivalent to:
05/31/2018 # 12:00am (UTC)
Please let me know possible solution.

Cron schedule in quartz to fire every week from a specific date for one year

I have a scenario, where I need to schedule a job using quartz which triggers every week from the date specified by the user and this should continue for exactly one year.
After going through Cron Schedule examples, I think below cron expression might help me:
eg. If date specified is 31-10-2015, then the expression would be:
" 0 30 20 31/7 10-10 ? 2015-2016 " which means starting from 31 Oct 3015, trigger after every 7 days for 1 year, ie. till 31 Oct 2016.
Please let me know if there are any issues with this expression.
Thanks.....
Your cron-expression is not valid as per CronMaker.Com. Looking at your cron expression, I have following things:
Your job fires at 8:30PM
It is weekly job running all 7 days of week
It ends in 2016
Here is the correct cron expression :
0 30 20 ? * 2,3,4,5,6,7,1 2015,2016 //Runs all days of week
To expire it on 31st Oct in 2016, you will have to provide Ending time while creating this job.
Update:
If you want to fire this job on a particular day of week, it will be something as below:
0 30 20 ? * MON 2015,2016 //Runs every week on monday
even i had same requirement, i implemented as below
we can run for every seven days from the start date, seven days when converted to hours, value is 168
JobDataMap jobDataMap = new JobDataMap();
jobDataMap.put("json", json);
String startDateStr = "2017-06-21 00:00:00.0";
Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(startDateStr);
String endDateStr = "2018-06-21 00:00:00.0";
Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(endDateStr);
JobDetail job = newJob(SimpleJob.class).withIdentity(name, "group1").build();
Trigger trigger = TriggerBuilder.newTrigger()
.startAt(startDate)
.withSchedule(
SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(168).repeatForever())
.endAt(endDate)
.usingJobData(jobDataMap)
.build();
sched.scheduleJob(job, trigger);
sched.start();
hope it helps!!

How do I get the Month End Personal Time Off Days used?

Using the Start Date and End Date of PTO - Personal Time Off Days Used only count days used up to end of prior month, excluding weekends and U.S Holidays in that certain month. Example of a Holiday is Sept 7th 2015 in the United States.
My goals are:
Create a Data Item Month End Personal Time Off Days used.
Of course it should be getting the number of PTO Days USED from the prior month only.
Exclude weekends in that certain month. So if the Resource takes a Leave on Friday and Monday, Saturday and Sunday should not be excluded in the computation.
How to exclude U.S Holidays, if this is possible that's great but if it's not possible then I'm okay with numbers 1, 2 and 3.
I have created a Data Item column that captures the PTO days used. But this is good for Year to date.
Case when [PTO Info].[PTO Audit].[PTOAuditTypeId] = 31571
and [PTO Info].[PTO Audit].[TimeOffTypeId] = 31566
then [PTO Info].[PTO Audit].[PTODays]
when [PTO Info].[PTO Audit].[PTOAuditTypeId]=31572
and [PTO Info].[PTO Audit].[TimeOffTypeId] = 31566
and [PTO Info].[PTO Audit].[PTODays] < 0
then abs([PTO Info].[PTO Audit].[PTODays] )
else 0 end
I'm not sure if the query below can help.
A calendar table is really going to help you out here. Assuming it has one record per calendar date, you can use this table to note weekends, holidays, fiscal periods vs Calendar periods, beginning of month/end of month dates. A number of things that can help simplify your date based queries.
See this question here for an example on creating a calendar table.
The main point is to create a data set with 1 record per date, with information about each date including Month, Day of Week, Holiday status, etc.
Without a calendar table, you can use database functions to generate your set of dates on the fly.
Getting the Month number for a date can be done with
extract([Month], <date field goes here> )
Getting a list of values from nothing will be required to generate your list of dates (if you don't have a calendar table with 1 record per date to use) will vary depending on your source database. In oracle I use a 'select from all_objects' type query to achieve this.
An example from Ask Tom:
select to_date(:start_date,'dd-mon-yyyy') + rownum -1
from all_objects
where rownum <=
to_date(:end_date,'dd-mon-yyyy')-to_date(:start_date,'dd-mon-yyyy')+1
For Sql Server refer to this stackoverflow question here.
Once you have a data set with your calendar type information, you can join it to your query above:
join mycalendar cal on cal.date >= c.PTOStartDate
and cal.date <= c.PTOEndDate
Also note, _add_days is a Cognos function. When building your source queries, try and use Native functions, like in oracle you can 'c.PTOStartDate + a.PTODays'. Mixing Cognos functions with native functions will sometime force parts of your queries to be processed locally on the Cognos server. Generally speaking, the more work that happens on the database, the faster your reports will run.
Once you have joined to the calendar data, you are going to have your records multiplied out so that you have 1 record per date. (You would not want to be doing any summary math on PTODays here, as it will be inflated.)
Now you can add clauses to track your rules.
where cal.Day_Of_Week between 2 and 6
and cal.Is_Holiday = 'N'
Now if you are pulling a specific month, you can add that to the criteria:
and cal.CalendarPeriod = '201508'
Or if you are covering a longer period, but wanting to report a summary per month, you can group by month.
Final query could look something like this:
select c.UserID, cal.CalendarPeriod, count(*) PTO_Days
from dbo.PTOCalendar c
join myCalendar cal on on cal.date >= c.PTOStartDate
and cal.date <= c.PTOEndDate
where cal.day_of_week between 2 and 6
and cal.Is_Holiday = 'N'
group by c.UserID, cal.CalendarPeriod
So if employee with UserID 1234 Took a 7 day vacation from thursday June 25th to Friday July 3th, that covered 9 days, the result you get here will be:
1234 201506 4
1234 201507 3
You can join these results to your final query above to track days off per month.

Resources