Get an Array of Dates of the Current Week Starting on Monday

Get an Array of Dates of the current week starting on Monday

You just need to get the first day of the week using iso8601 calendar where the first weekday is Monday and add from 0 to 6 days to it. Try like this:

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
extension Date {
var startOfWeek: Date {
return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
}
var daysOfWeek: [Date] {
let startOfWeek = self.startOfWeek
return (0...6).compactMap{ Calendar.current.date(byAdding: .day, value: $0, to: startOfWeek)}
}
}

Date().daysOfWeek  // ["Aug 13, 2018 at 12:00 AM", "Aug 14, 2018 at 12:00 AM", "Aug 15, 2018 at 12:00 AM", "Aug 16, 2018 at 12:00 AM", "Aug 17, 2018 at 12:00 AM", "Aug 18, 2018 at 12:00 AM", "Aug 19, 2018 at 12:00 AM"]

How do I get an array of all days in the week given the current date in javascript?

Create an array with 7 elements, subtract the weekday and add the index as day:

function selectWeek(date) {
return Array(7).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}

const date = new Date();
console.log(selectWeek(date));

Get array of days by week number starting on Mondays in JavaScript

You're assuming that January 1st of each year starts on a monday. This piece of code automatically finds the first monday of each year.

var year = 2016;var week = 1;var index = 1;var options = {  weekday: 'long',  year: 'numeric',  month: 'long',  day: 'numeric'};var d = new Date(year, 0, index + (week - 1) * 7);var weekday = d.getDay();var diff = 1 - weekday;if (diff < 0) {  diff = diff + 7;}d.setDate(d.getDate() + diff);
console.log(d.toLocaleString(undefined, options));

How to get the ALL the dates of the current week?

Something like that ?

Array.from(Array(7).keys()).map((idx) => {const d = new Date(); d.setDate(d.getDate() - d.getDay() + idx); return d; });

Some explanation, Array(7) will create an empty array with 7 entries.

Array(7).keys() will return an iterator with the array keys.

Array.from(Array(7).keys()) will transform the iterator into a new array with 7 entries containing integers (aka [0, 1, 2, 3, 4, 5, 6])

d.getDate() - d.getDay() + idx, we take the current day (23), remove the day of week (0 for Sunday, 2 for Tuesday... Basically we calculate the last Sunday date) et add number of days to have every date in the week.

How to get first and last day of the current week in JavaScript

var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6

var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"

This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.

Making it work with first and last days in different months is left as an exercise for the user

How to make an array of the current week dates Swift

You can get today's yearForWeekOfYear and weekOfYear calendar components and construct a new date from it. It will give you the first day of the week. If you want your week to start from Monday you need to use iso8601 calendar, if you would like to have your week to start on Sunday you can use Gregorian calendar. To avoid some extreme cases you should do all your calendrical calculations using noon time. Not all dates starts at midnight.

let dateComponents = Calendar(identifier: .gregorian).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date())
let startOfWeek = Calendar(identifier: .gregorian).date(from: dateComponents)!
let startOfWeekNoon = Calendar(identifier: .gregorian).date(bySettingHour: 12, minute: 0, second: 0, of: startOfWeek)!
let weekDays = (0...6).map { Calendar(identifier: .gregorian).date(byAdding: .day, value: $0, to: startOfWeekNoon)! }
weekDays // ["Jun 7, 2020 at 12:00 PM", "Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM"]

Expanding on that you can extend Date and create some helpers:

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
static let gregorian = Calendar(identifier: .gregorian)
}

extension Date {
func byAdding(component: Calendar.Component, value: Int, wrappingComponents: Bool = false, using calendar: Calendar = .current) -> Date? {
calendar.date(byAdding: component, value: value, to: self, wrappingComponents: wrappingComponents)
}
func dateComponents(_ components: Set<Calendar.Component>, using calendar: Calendar = .current) -> DateComponents {
calendar.dateComponents(components, from: self)
}
func startOfWeek(using calendar: Calendar = .current) -> Date {
calendar.date(from: dateComponents([.yearForWeekOfYear, .weekOfYear], using: calendar))!
}
var noon: Date {
Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
func daysOfWeek(using calendar: Calendar = .current) -> [Date] {
let startOfWeek = self.startOfWeek(using: calendar).noon
return (0...6).map { startOfWeek.byAdding(component: .day, value: $0, using: calendar)! }
}
}

usage:

// this will give you all days of the current week starting monday
Date().daysOfWeek(using: .iso8601) // ["Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM", "Jun 14, 2020 at 12:00 PM"]
// this will give you all days of the current week starting sunday
Date().daysOfWeek(using: .gregorian) // ["Jun 7, 2020 at 12:00 PM", "Jun 8, 2020 at 12:00 PM", "Jun 9, 2020 at 12:00 PM", "Jun 10, 2020 at 12:00 PM", "Jun 11, 2020 at 12:00 PM", "Jun 12, 2020 at 12:00 PM", "Jun 13, 2020 at 12:00 PM"]

To convert your date to a fixed date format you can create a custom date formatter extending Formatter and Date:

extension Formatter {
static let ddMMyyyy: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "dd.MM.yyyy"
return dateFormatter
}()
}

extension Date {
var ddMMyyyy: String { Formatter.ddMMyyyy.string(from: self) }
}

Now you can simply map your dates using the KeyPath:

Date().daysOfWeek(using: .gregorian).map(\.ddMMyyyy) // ["07.06.2020", "08.06.2020", "09.06.2020", "10.06.2020", "11.06.2020", "12.06.2020", "13.06.2020"]

Get the dates for this current week and the next one

it looks like your are misusing your index "i" in the for loop. "days" is not an array, it is an integer. Try the following:

let twoWeeks = [];let days = 14;let today = new Date;let calcDate = new Date(today.setDate(today.getDate() - today.getDay()));
for(let i=0; i<days; i++) { calcDate.setDate(calcDate.getDate() + 1) twoWeeks.push(new Date(calcDate))}
console.log(twoWeeks)

Javascript - How do i get every date in a week from a given week number and year

Here's an example building on top of: javascript calculate date from week number

Get the first date of the week, then return an array of 7 elements, incrementing the date for each element.

If the day number goes above the number of days in the month, then add one to the month temp.m and reset the day temp.d equal to one.

function getISOWeek(w, y) {
var simple = new Date(y, 0, 1 + (w - 1) * 7);
var dow = simple.getDay();
var ISOweekStart = simple;
if (dow <= 4)
ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
else
ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
const temp = {
d: ISOweekStart.getDate(),
m: ISOweekStart.getMonth(),
y: ISOweekStart.getFullYear(),
}
//console.log(ISOweekStart)
const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()

return Array.from({length: 7}, _ => {
if (temp.d > numDaysInMonth){
temp.m +=1;
temp.d = 1;
// not needed, Date(2020, 12, 1) == Date(2021, 0, 1)
/*if (temp.m >= 12){
temp.m = 0
temp.y +=1
}*/
}
return new Date(temp.y, temp.m, temp.d++).toUTCString()
});
}

// var weekNumber = "week + " " + year"; //"35 2020"
const weekNumber = "53 2020";

const weekYearArr = weekNumber.split(" ").map(n => parseInt(n))

const weekOut = getISOWeek(...weekYearArr)

console.log(weekOut);


Related Topics



Leave a reply



Submit