how to check that date is over 18 and under 100? - javascript

how to check that date is over 18 and under 100 or what methods need to use from date-fns? i tried to use this solution:
dateIsAfter18AndBefore100: (value) => {
const date = value.replace(/(\d+).(\d+).(\d+)/, '$3/$2/$1')
if (!(isAfter(subYears(new Date(), 18), new Date(date)) && isBefore(subYears(new Date(), 100), new Date(date)))) {
return createTranslatable('validationDateIsBeforeCurrentDate');
}
},
``` but it not react on days and months, only years

Related

Javascript to get the previous working day. Returns undefined

Been knocking my head for a few hours searching for a solution. Why would prevDate return undefined? Just don't understand what I am missing.
async function prevDate(date) {
date.setDate(date.getDate()-1)
if (date.getDay() == 0 || date.getDay() == 6) {
prevDate(date)
} else {
console.log("date: ", date, "day: ", date.getDay())
return (date)
}
}
date = new Date("2021-09-20T00:00:00")
prevDate(date)
.then((res) => {
console.log("res: ", res) //undefined
})
.catch((err) => {
console.log(err)
})
output
date: 2021-09-17T04:00:00.000Z day: 5
res: undefined
The other people stated the reason your code doesn't work. But I'm wondering why you are using an async function for code that is not asynchronous. If you still want to use a recursive function it can be simply written like this:
function prevDate (date) {
date.setDate(date.getDate() - 1);
if (!(date.getDay() % 6)) {
return prevDate(date);
} else {
console.log(`date: ${date} day: ${date.getDay()}`);
return date;
}
}
const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);
Or you can simplify it even further:
const prevDate = (date) => {
date.setDate(date.getDate() - 1);
return !(date.getDay() % 6) ? prevDate(date) : date;
};
const date = new Date("2021-09-20T00:00:00");
console.log(`res: ${prevDate(date)}`);
You can write a simple function that subtracts 1, 2 or 3 days depending on which day of the week the date is on, e.g.
// Return previous work day (i.e. not Sat or Sun)
function getPreviousWorkDay(d = new Date()) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - ({1:3, 0:2}[d.getDay()] || 1)
);
}
// Examples over year and month end
[new Date(2020,11,28), // Mon
new Date(2020,11,29), // Tue
new Date(2020,11,30), // Wed
new Date(2020,11,31), // Thu
new Date(2021, 0, 1), // Fri
new Date(2021, 0, 2), // Sat
new Date(2021, 0, 3), // Sun
].forEach(d =>
console.log(`${d.toDateString()} => ${getPreviousWorkDay(d).toDateString()}`)
);

date-fns - countdown from date including weeks

I am building a countdown clock, and I am using date-fns. I need to be able to countdown from a date including the number of weeks. The documentation here looks like formatDuration returns the number of weeks but doesn't seem to and wonder if I need to use something else?
I'm aware of the differenceInWeeks function they provide, but not sure how suitable that would be in my case.
Thanks in advance.
import { intervalToDuration, formatDuration } from 'date-fns';
const units = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'];
let duration = intervalToDuration({
start: new Date(2022, 6, 2, 0, 0, 15),
end: new Date(),
});
formatDuration(duration, {
format: units,
delimiter: ', ',
});
// Returns years, months, days, hours, minutes and seconds but not weeks
When creating a duration, date-fns doesn't add weeks by default and if they aren't in the duration, the formatter won't show them.
You can manually add weeks using a function based on the value for days, e.g.
function addWeeks(duration) {
if (!duration.weeks) {
duration.weeks = duration.days / 7 | 0;
duration.days = duration.days - duration.weeks*7;
}
}
You may want to test if duration.days exists before using it. Then do something like:
let duration = intervalToDuration({
start: new Date(2022, 6, 2, 0, 0, 15),
end: new Date()
});
// Add weeks if missing
addWeeks(duration);
let formattedDuration = formatDuration(duration, {
format: units,
delimiter: ', '
});
// "1 year, 9 months, 1 week, 1 day, 10 hours, 39 minutes, 27 seconds"
console.log(formattedDuration);

Check if a date from a collection is 3, 6, or 9 months (and so on) ago

Must check if a collection of projects contains a startDate that has passed 3, 6, and so on, months, using moment.js but having problems coming up with a way to calculate the difference in time between today and startDate, was thinking of seeing if (today / startDate) % 3 === 0 but I don't think that's the best way and the results are not as expected. Even using moment.js diff, like this doesn't yield desired results and logs projects that clearly haven't elapsed elapsed 3, 6 etc... months.
Obviously I'm missing something would appreciate some help thank you.
const today = moment()
const projects = await ProjectModel.find()
projects.forEach(project => {
if (today.diff(moment(project.startDate), "month") % 3 == 0) {
console.log(project)
}
})
% is the wrong way to go about it. You want to find the 3 month ago bracket that the date falls in, so get the difference in months and divide by 3 and floor the result. If diff < 3, you'll get 0. If 3 <= diff <6 months, you'll get 1, etc.
E.g.
let projects = [
{startDate: new Date(2017,10,1)}, // 1 Nov 2017
{startDate: new Date(2018,10,1)}, // 1 Nov 2018
{startDate: new Date(2019, 0,1)}, // 1 Jan 2019
{startDate: new Date(2019, 3,1)}, // 1 Apr 2019
{startDate: new Date(2019, 4,1)}, // 1 May 2019
{startDate: new Date(2019, 6,1)}, // 1 Jul 2019
{startDate: new Date(2019, 7,1)} // 1 Aug 2019
];
let today = moment();
projects.forEach(project => {
let diff = today.diff(moment(project.startDate), "month") / 3 | 0;
console.log(
moment(project.startDate).format('DD-MMM-YYYY') +
' was ' + (diff * 3) + ' to ' +
(++diff * 3) + ' months ago'
);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
The modulo makes sense to me. If you roll your own dates, it works like this (plus or minus a leap-year-day, which is what libraries like moment.js are good at abstracting away):
const projects = [
{ id: 1, startDate: 1551441600000 },
{ id: 2, startDate: 1554120000000 },
{ id: 3, startDate: 1556712000000 },
{ id: 4, startDate: 1559390400000 },
{ id: 5, startDate: 1564660800000 }
];
// Gets current year, month, and date
const now = new Date(),
thisYear = now.getFullYear(),
thisMonth = now.getUTCMonth(),
thisDate = now.getUTCDate();
// Loops through projects
projects.forEach(project => {
// Gets year, month, and date for each project
const then = new Date(project.startDate),
startYear = then.getFullYear(),
startMonth = then.getUTCMonth(),
startDate = then.getUTCDate();
//console.log(then.toUTCString());
// Reports on the project if it started on an earlier day of the month 3, 6, etc months ago
const justStarted = thisYear == startYear && thisMonth == startMonth,
isQuarterInterval = thisMonth % 3 == startMonth % 3 && thisDate >= startDate
if(isQuarterInterval && !justStarted){
console.log("Project #" + project.id + " started " + then);
}
});

List of days between two dates in typescript

I try to create a list of days between two days.
I created solution like this:
this.daysBetween = [];
while (dateFrom.getDate() !== dateTo.getDate()+1 ) {
this.daysBetween.push(this.dateFrom);
dateFrom.setDate(dateFrom.getDate()+1);
}
But it works only in 90% cases (if there is month change it doesn't work)
e.g. when I pick dates:
dateFrom: 29 august
dateTo: 30 august
it prints me days from 29 august till 30 september ignoring 31 august ...
Any ideas how to fix my solution, or maybe there is better one?
EDIT:
My question is different than question suggested, because in my question I have as input two dates
e.g.
let dateFrom = new Date(2018, 9, 29);
let dateTo = new Date(2018, 9, 30);
On suggested duplicate result of this could have been int number 1
My question is how to loop through all days between two dates (dateFrom, dateTo)
Where result of those 2 dates examples (dateFrom, dateTo) would've been list with 2 elements:
Mon Oct 29 2018 00:00:00 GMT+0100
Tue Oct 30 2018 00:00:00 GMT+0100
Simple Typescript Solution is given below
Javascript version on Github
class MyDate {
dates: Date[];
constructor() {
this.dates = [];
}
private addDays(currentDate) {
let date = new Date(currentDate);
date.setDate(date.getDate() + 1);
return date;
}
getDates(startDate: Date, endDate: Date) {
let currentDate: Date = startDate;
while (currentDate <= endDate) {
this.dates.push(currentDate);
currentDate = this.addDays(currentDate);
}
return this.dates;
}
}
let md = new MyDate();
let daysBetween: Date[] = md.getDates(new Date(2018, 7, 22), new Date(2018, 8, 30));
console.log(daysBetween);
You could use moment's duration:
/**
* Get an array of moment instances, each representing a day beween given timestamps.
* #param {string|Date} from start date
* #param {string|Date} to end date
*/
function daysBetween(from, to) {
const fromDate = moment(new Date(from)).startOf('day');
const toDate = moment(new Date(to)).endOf('day');
const span = moment.duration(toDate.diff(fromDate)).asDays();
const days = [];
for (let i = 0; i <= span; i++) {
days.push(moment(fromDate).add(i, 'day').startOf('day'));
}
return days;
}
const days = daysBetween('29-Aug-2018', '30-Sep-2018');
console.info(days.map(d => d.toString()).join('\n'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can alter the loop start/end condition to include/exclude the first/last day.
Update:
Using Luxon instead:
const DateTime = luxon.DateTime;
function daysBetween(start,end){
dateStart = DateTime.fromJSDate(start);
dateEnd = DateTime.fromJSDate(end);
diffDays = dateEnd.diff(dateStart,'days');
const days = [];
for(let i = 0 ; i < diffDays.days; i++){
days.push(new Date(dateStart.plus({days:i+1}).toMillis()));
}
return days;
}
console.log(daysBetween(new Date('23-Feb-2020'),new Date('5-Mar-2020')));
<script src="https://cdn.jsdelivr.net/npm/luxon#2.3.0/build/global/luxon.min.js"></script>
You could calculate the difference in milliseconds, and then convert that into the difference in days.
You can then use this to fill an array with Date objects:
const MS_PER_DAY: number = 1000 x 60 x 60 x 24;
const start: number = dateFrom.getTime();
const end: number = dateTo.getTime();
const daysBetweenDates: number = Math.ceil((end - start) / MS_PER_DAY);
// The days array will contain a Date object for each day between dates (inclusive)
const days: Date[] = Array.from(new Array(daysBetweenDates + 1),
(v, i) => new Date(start + (i * MS_PER_DAY)));

Increment date by one day to a set epoch date

I would like to increment a (epoch) date by one day.
So far I have:
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
This spits out 25 so I am on the right track. How would I convert it back to a Date object?
This is going to be in this map function:
return data.map(t => ({
id: t.id,
start_date: new Date(parseInt(t.date_created, 10)),
duration: // here, taking the above start date and adding one day
)
}));
I think you can add day in milliseconds to achieve this.
let date = "1535162451650"; // August 24 2018
console.log(new Date(parseInt(date, 10)).getDate() + 1);
let nextDay = +date + (24 * 60 * 60 * 1000) // 1 day in millisecond
nextDay = new Date(nextDay)
console.log(nextDay)
You can also use momentjs in following way:
var date = 1535162451650
date = moment(abc)
console.log('date', date.format('DD MM YYYY'))
date = date.add(1, 'day')
console.log('date', date.format('DD MM YYYY'))
How about this?
var options = {
id: t.id,
start_date: new Date(parseInt(t.date_created, 10))
};
options.duration = new Date(options.start_date.getTime());
options.duration.setDate(options.duration.getDate() + 1);
return data.map(t => (options));
I think I figured it out. Looks ugly but seems to work
let date = "1535162451650";
console.log(new Date (new Date(parseInt(date, 10)).setDate(new Date(parseInt(date, 10)).getDate() + 1)));
// gives me aug 25 2018
Is there a cleaner way to do this? haha

Categories

Resources