Create days array from Today till seven days ago with date-fns - javascript

In my React component, I have to render a list of days: from Today - seven days ago.
Like: Today / Yesterday / Monday / Tuesday / Wednesday / Thursday / Friday.
I am using date-fns.
const generateDays = () => {
const date: Date = new Date();
const a = subDays(date, 4);
const formatted = format(a, 'eeee', { locale: nl });
return formatted;
};
How do I accomplish this in an smooth way?
What I tried:
const today = new Date();
const sevenDaysAgo = subDays(today, 6);
const sevenDays = eachDayOfInterval({ start: sevenDaysAgo, end: today });
sevenDays.forEach((day) => {
console.log(format(day, 'eeee', { locale: nl }));
});
This returns:
['Wednesday', 'Tuesday', 'Monday', 'Sunday', 'Saturday', 'Friday', 'Thursday']

To get the week day from the dayOffset (replace 'en-us' with your country's code if you're not American) you can do the following.
const offset_date = new Date();
offset_date.setDate(offset_date.getDate() + dayOffset);
const week_day = offset_date.toLocaleString('en-us', {weekday: 'long'});

You can use the formatRelative function from the date-fns library, it formats the dates in words from a given date.
Here is a code sandbox link that might be helpful.

Related

Get last 7 days by names javascript

How to get the last seven days, from today, (by names) in java script.
like if today is Wednesday, I want to get it like (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday).
Just add the days in the string array and iterate them backward by getting current date with new Date() this will return the index of current day
const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const d = new Date();
let day = weekday[d.getDay()];
var wanteddays = 8;
var temp = d.getDay()
while(wanteddays!=0){
if (temp <0)
temp = 6;
console.log(weekday[temp]);
temp = temp-1;
wanteddays = wanteddays -1;
}
function getDayName(date, len, local) {
let newDate = new Date(date);
let weekDays = [];
Array(len).fill(1).forEach((subDay) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
to use:
getDayName(Date.now(), 7, 'en-EN')
OR
getDayName('10/12/2022', 7, 'en-EN')
Typescript:
function getDayName(date: Date | string | number, len: number, local:string) {
let newDate = new Date(date);
let weekDays: string[] = [];
Array(len).fill(1).forEach((subDay: number) => {
newDate.setDate(newDate.getDate() - subDay);
weekDays.push(newDate.toLocaleDateString(local, { weekday: 'long' }));
})
return weekDays;
}
This should order an array to follow your wished output.
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var currentDay = days[ (new Date()).getDay()]
days = days.reverse();
var x = days.indexOf(currentDay)
var daysLastSeven = days.slice(x).concat(days.slice(0,x))
console.log(daysLastSeven)

How do I get the days between the today's day and the last day of the month using Moment.js?

Here's the code that I have right now:
const moment = require('moment')
const m = moment
const currDay = m().format('D')
const dayOfWeek = m().format('dddd')
const daysInMonth = m().daysInMonth()
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');
I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example: Wed 8, Thu 9, Fri 10 ... Fri 31.
I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...
const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.
function getMonthEnd(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
function getMonthDaysLeft(date = new Date()) {
return getMonthEnd(date).getDate() - date.getDate();
}
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);
To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:
function getMonthDaysLeftAsList(date = new Date()) {
let d = new Date(+date);
// Formatter
let f = new Intl.DateTimeFormat('en',{
day: 'numeric',
month: 'short'
});
let m = d.getMonth();
let dayList = [];
while (d.getMonth() == m) {
dayList.push(f.format(d));
d.setDate(d.getDate() + 1);
}
return dayList;
}
console.log(getMonthDaysLeftAsList());

date-fns Format Date and Age calculation problem in React

I was using "moment.js" in my project (like age calculator), but I want to replace it with "date-fns".
Using moment.js, I formatted the input value as DD / MM / YYYY (for TR) and was calculating the age by subtracting the current date but right now I am having trouble doing this with date-fns. I felt like moment.js came easier to use.
Moment.js age calculator codes: I entered the input on 10/03/1998. (DD/MM/YYYY -> Turkey)
const birthDay = moment(value, 'DD/MM/YYYY');
console.log(birthDay); // (output: 10/03/1998)
const now = moment();
console.log(now); // (output: Thu Mar 04 2021 10:40:09 // TR Local Time)
const age = moment.duration(now.diff(birthDay)).years();
console.log(age); // (output: 22)
I tried to do it with date-fns but was not successful. I can not calculate the age.
const birthDay = format(new Date(value), 'dd/MM/yyyy');
console.log(birthDay); // (output: 03/10/1998 - **issue 1**)
const now = new Date();
console.log(now); // (output: Thu Mar 04 2021 10:45:18 // TR Local Time)
const age = differenceInCalendarYears(now, birthDay);
console.log(age); // (output: NaN - - **issue 2**)
I would appreciate it if you could help with date-fns.
I edited for the answer, right now it's like this:
const birthDay = new Date(value);
console.log(birthDay); // Oct 03 1998 (03/10/1998) it's MM/DD, I want DD/MM
const now = new Date();
console.log(now); // Mar 04 2021
const age = differenceInCalendarYears(now, birthDay);
console.log(age); // it should be 22 but 23.
Your age depends on whether you had your anniversary on the current year. That's why you should NOT use differenceInCalendarYears to calculate the age: it does not take into account the current month and day, only the year.
Use differenceInYears instead, or intervalToDuration if you want to get the age including months and days.
const { differenceInCalendarYears, differenceInYears, intervalToDuration, parse } = require("date-fns")
function calculateAge(dob) {
const date = parse(dob, "dd/MM/yyyy", new Date());
const age = differenceInYears(new Date(), date);
return age;
}
// INCORRECT
function calculateAge2(dob) {
const date = parse(dob, "dd/MM/yyyy", new Date());
const age = differenceInCalendarYears(new Date(), date);
return age;
}
console.log("dob = 01/04/2000"); // Running on 2021-08-05
console.log('- using differenceInYears: ', calculateAge("01/04/2000")); // 21
console.log('- using differenceInCalendarYears: ', calculateAge2("01/04/2000")); // 21
console.log("dob = 01/10/2000"); // Running on 2021-08-05
console.log('- using differenceInYears: ', calculateAge("01/10/2000")); // 20
console.log('- using differenceInCalendarYears: ', calculateAge2("01/10/2000")); // 21
function calculateFullAge(dob) {
const birthDate = parse(dob, "dd/MM/yyyy", new Date());
const { years, months, days } = intervalToDuration({ start: birthDate, end: new Date()});
return { years, months, days };
}
// Running on 2021-08-05
console.log('- using intervalToDuration: ', calculateFullAge("01/04/2000")); // {years: 21, months: 4, days: 4}
console.log('- using intervalToDuration: ', calculateFullAge("01/10/2000")); // {years: 20, months: 10, days: 4}
You can run this in the following runkit
I recently had a similar situation & this is how I implemented it
import { differenceInYears, parse } from "date-fns"
const calculateAge = (dob: string): number => {
const date = parse(dob, "dd/MM/yyyy", new Date())
const age = differenceInYears(new Date(), date)
return age
}
calculateAge("11/11/2019") // returns 2
PS: consider removing types (:string & :number) if you're only using JS
Try this ;)
import { intervalToDuration } from "date-fns"
const calculateAge = (dob: string): number => {
const interval = intervalToDuration({
start: new Date(dob),
end: new Date(),
})
return interval.years ? interval.years : 0
}
Your problem is parsing the date string (timestamp) using:
const birthDay = new Date(value);
It's strongly recommended not to use the built–in parser, see Why does Date.parse give incorrect results?
Since you're using Date.fns, use it for parsing too.
And as #volpato points out, you should use differenceInYears not differenceInCalendarYears as the later is effectively just currentDate.getFullYear() - birthday.getFullYear():
let dateFns = require("date-fns")
let d = '10/03/1998'; // 10 Mar 1998
let date = dateFns.parse(d, 'dd/MM/yyyy', new Date());
let age = dateFns.differenceInYears(new Date(), date);
console.log(age); // 23 when run on 4 Mar 2021
The above can be run at npm.runkit.com

Conditional date in a string based on distance to date?

Searching for this didn't bear much fruit. Hopefully you can help!
I'm looking to generate sentences like this:
The next Monday session starts on Monday October 19th[1] and runs for 7 weeks until Monday November 30th[2]
where [1] is the date of the next Monday, unless that Monday is 4 days or less in the future, in which case it will be the following Monday. And, [2] is 7 weeks after the Monday mentioned in [1].
As a bonus if it worked for other days of the week it would be awesome!
The dates can be based on the client browser. I'm hoping to implement this entirely in client side JS for a website.
Any help or pointers in the right direction?
let date = new Date();
let nextMonday = new Date();
let daysToNextMonday = new Date();
nextMonday.setDate(date.getDate() + (1 + 7 - date.getDay() % 7));
let diffTime = Math.abs(nextMonday - date);
daysToNextMonday = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); //full days, no fractions
if (daysToNextMonday <= 4) {
nextMonday.setDate(nextMonday.getDate() + 7);
}
let sevenWeeksAfter = new Date(nextMonday);
sevenWeeksAfter.setDate(nextMonday.getDate() + 7 * 7);
const monthNextMonday = new Intl.DateTimeFormat('en', {
month: 'long'
}).format(nextMonday);
const dayNextMonday = new Intl.DateTimeFormat('en', {
day: '2-digit'
}).format(nextMonday);
const monthSevenWeeksAfter = new Intl.DateTimeFormat('en', {
month: 'long'
}).format(sevenWeeksAfter);
const daySevenWeeksAfter = new Intl.DateTimeFormat('en', {
day: '2-digit'
}).format(sevenWeeksAfter);
let text = `The next Monday session starts on Monday ${monthNextMonday} ${dayNextMonday}th and runs for 7 weeks until Monday ${monthSevenWeeksAfter} ${daySevenWeeksAfter}th`;
console.log(text);

JS dates, first day of the month

i'm programming a calendar and i need to know what the first day of each month is. Like, This month, hte first day was on a sunday. How would i go about to figure that out for all months of the year? Or any month for that matter.
Thanks in advance!
edit: the day can be returned as an integer.
Where options for toLocaleString are supported, you can use it to get the day name in the browser default language:
function getDayName(date) {
return date.toLocaleString(undefined, {weekday:'long'});
}
function getMonthName(date) {
return date.toLocaleString(undefined, {month:'long'});
}
// Create a date
var d = new Date();
// Set to first of month
d.setDate(1);
// Create string
console.log(`The first of ${getMonthName(d)} was a ${getDayName(d)}.`);
Of course mixing English with some other language may not be appropriate…
You could create a method that returns the day name
function(year, month){
var date = new Date(year, month, 1);
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[date.getDay()];
}
JavaScript already provides this out of the box be using getDay.
new Date().getDay()
This will return 0-6. Depends on what weekday it is.
If you need it as a readable string you may want to do something like this:
var weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
console.log(weekdays[new Date().getDay()]);
Knowing this you can go furter:
const year = new Date().getFullYear();
const weekdays = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
[0,1,2,3,4,5,6,7,8,9,10,11].forEach(x => {
const weekday = new Date(year, x, 1).getDay();
console.log(weekdays[weekday]);
});
See: MDN
I would highly recommend using MomentJS library if you are not already using it. Using moment, you can get the day of 1st of any month using this single statement:
moment("2017-11-01").startOf('month').format("dddd")
If you cannot use moment for some reason, then you could just create a function that takes in month and year and returns back the day of 1st of that month. You need to use Date.prototype.getDay() for this, which returns a value from 0 to 6, where 0 means Sunday.
$("#get-day").on("click", function(e){
var year = $("#year").val();
var month = $("#month").val();
alert( getDay(year, month) );
});//#get-day click()
function getDay(year, month){
var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"];
var dayIndex = new Date(year + "-" + month + "-01").getDay();
return days[ dayIndex ];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="year" value="2017" />
<input type="text" id="month" value="10" />
<button id="get-day">Get Day on 1st</button>
The .getDay() method returns an integer, the day of the week for the specified date according to local time, where Sunday = 0 and Saturday = 6. Here's an example using this:
dateFunction = function(myDate){
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
var dayInt = new Date(myDate).getDay()
return days[dayInt]
}
var FirstDayOfOctober = dateFunction("2017-10-01");

Categories