How to get weeks array within two dates with moment.js? - date

I have two dates, starting and an end date. I want to calculate an array of weeks like
let startDate = "2022-01-03";
let endDate = "2022-01-22";
// required result
const result = ["01-03","01-10","01-17","01-24"]

Related

How to query data that has a timestamp that is less than n hours?

Currently my method for determining wether data is older than n hours uses this code after getting a timestamp from a document:
let timestamp = i.get("timestamp") as! Timestamp
let lastUpdatedDate = timestamp.dateValue()
let currentDate = Date()
let cal = Calendar.current
let components = cal.dateComponents([.hour], from: lastUpdatedDate, to: currentDate)
let diff = components.hour!
Usually this code is executed in a for each loop per each document after getting the documents from firestore.
Is there a way to query data using the field timestamp and checking if it is less than n hours instead?
ref.collection("References").whereField("timestamp", isLessThanOrEqualTo: n hours)
If you want a value to compare it against, you can do:
let date = Date().addingTimeInterval(-4 * 60 * 60)
Or you can do:
let date = Calendar.current.date(byAdding: .hour, value: -4, to: Date())
You may have to convert those to a Timestamp from this Date object, e.g., presumably something like:
let timestamp = Timestamp(date)

How can I filter a Realm List by Date Swift NSPredicates

I want to filter my Realm List by Date. The Filter should show me every listed Item by month. I select the month "June" and the app should show me everything that was sold in June.
this is the code I tried but it obviously doesnt worked out.
let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
let formattedDate = format.string(from: date)
print(formattedDate)
let current = Calendar.current
let componentDate = current.component(.month, from: date)
print(current.component(.month, from: date))
let articles = realm.objects(Article.self).filter("artSoldDate = \(componentDate)")
return articles
You would need to use a date range filter. You would need to start the range at a specific date and end it at a certain date. For example,
let predicate = NSPredicate(format: "artSoldDate >= %# AND artSoldDate <= %#", startDate, endDate)
let result = realm.objects(Art.self).filter(predicate)
Your example seems to try and check when the artSoldDate is exactly some date.

Extract entity from last seven days core data

I am currently working with core data to store meals. My entities are date (Date), foods (string) and drinks (string). Now I want to extract all the foods stored for the last seven days. How would I do this? I know i should somehow use NSPredicate, but I can't figure out how exactly.
Get the current calendar
let calendar = NSCalendar.currentCalendar()
Get the current date
let now = NSDate()
Subtract 7 days from current date
let sevenDaysAgo = calendar.dateByAddingUnit(.Day, value: -7, toDate: now, options: [])!
Get the start of the day 7 days ago
let startDate = calendar.startOfDayForDate(sevenDaysAgo)
Create the predicate, literal date is the Core Data attribute
let predicate = NSPredicate(format:"(date >= %#) AND (date < %#)", startDate, now)

Date query with the current date between two date_time columns

I have a fusion table with two date_time columns. The fist one is the start date (Startdatum) and in the other column is the end date (Einddatum).
I want to do a query with the current date, and only show the KML-lines on a map where the current date lies between the start and end date.
I tried to use the code below to create a string with a date format:
var time_date = new Date();
var day = time_date.getDate();
var month = time_date.getMonth()+1;
var year = time_date.getFullYear();
var date = (year+"."+month+"."+day);
To show the KML-lines on the map I tried to use the following code:
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col2",
from: "1mOMP1seJq4FdiNTugsfylZaJc8sKcSlfJKUuTJjv",
where: "'Startdatum' <= date AND 'Einddatum' >= date"
},
options: {
styleId: 2,
templateId: 2
}
});
Unfortunatly the map shows all the KMS-lines regardless what date is in one of the columns.
What am I doing wrong?
the where-clause is wrong, it has to be
where: "Startdatum <= '"+date+"' AND Einddatum >= '"+date+"'"
the date-format seems to be wrong. Although the used format yyyy.MM.dd is defined in the documentation, it doesn't work. The format yyyy-MM-dd currently works for me(but it's not defined in the documentation).
var date = (year+"-"+month+"-"+day);
(in case that day and month be less than 10 they wouldn't match the pattern, but that doesn't seem to be an issue)
Beyond that: when you fix these 2 mentioned parts it currently works(for me), but I've tried it a couple of hours ago and got unstable results.

using datetime object as an argument

I have been struggling to understand how to use datetime objects. I want to use datetime.date instances as keys in a dictionary. I then want to be able to return dates within specified ranges using datetime.delta.
My first conundrum is when I create an object to be entered into the dictionary.
class Work_day():
'''input a workday , date and hours worked'''
def __init__(self, date, hours, rate):
self.date = datetime.date()
self.hours = hours
self.rate = rate
I want self.date to be a datetime.date object but datetime.date takes 3 argument (year, month, day) so what is the correct syntax for the def_init_ argument 'date'?
Then I assume when I change how that is written in the Work_day class then I will have to modify my code when I create instances of it in the Timesheet class e.g. in add_work_day() method
class Timesheet():
'''Represent a collection of workdays'''
def __init__(self):
self.timesheet = {}
def add_work_day(self, date, hours,rate):
'''adds a record of a work day into the timesheet dictionary'''
day = Work_day(date, hours, rate)
if day.date in self.timesheet:
print("There is already an entry for this day. ")
else:
self.timesheet[day.date] = hours, rate
I've been researching the python docs and scouring books but I'm not getting it! Need some help.
I also have a method that prints a range of the workdays in the timesheet. I made it work when I subbed the date key for a simple int. here it is (in ''' ''') with a shonky attempt at a datetime delta underneath
def show_days(self):
'''shows a user defined range of dates and the total pay for that period'''
pp = pprint.PrettyPrinter()
date_from = input("From date: ")
date_to = input("To date: ")
t = self.timesheet
total = 0
'''for dates in range(date_from, date_to + 1):
if dates in t:
total += self.sum_day(dates)
pp.pprint((dates, t[dates)])
print("Total £", total)'''
date = date_start = datetime.date(date_from)
date_end = datetime.date(date_to)
while date <= date_end:
if date in t:
print(date, t[dates])
date += datetime.timedelta(days=1)
I hope someone can find the patience to talk me through this. Cheers.
If you assign the date with self.date = datetime.date(*date), then you can create a Work_day by passing a (year,month,day) tuple:
day = Work_day((2013,5,31), 8.0, 8.25)
Alternatively, if you want the input to be a date string, use datetime.strptime, an appropriate formatting string, and the date() method to get a date object:
self.date = datetime.datetime.strptime(date,'%m/%d/%Y').date()
...
date = Work_day('5/31/2013', 8.0, 8.25)
Finally, you could just pass a date object:
day = Work_day(datetime.date(2013,5,31), 8.0, 8.25)
...
self.date = date
The Timesheet class should work after any of these changes. show_days still needs some work, but I'll leave that as an exercise. Hint: Parse the input dates with strptime.