Realm Javascript filtered on Date but ignore year - realm

I am attempting to query in RealmJS on a Date field for birthdays.
I want to find all the people that have a birthday today.
The problem is that I can't ignore the year. Is there a way to do this?
My code:
const today = new Date();
const morning = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0,0,0,0);
const evening = new Date(today.getFullYear(), today.getMonth(), today.getDate()+1, 0,0,0,0);
const studentBirthdaysToday = realm.objects('Student').filtered('birthday >= $0 && birthday < $1', morning, evening);
Even though there are students with a birthday today, it doesn't show because it's looking for the year 2020.
How can I ignore the year?
This is how student.birthday is formatted in the database, it's a Realm Date:
2000-08-25T10:00:00.000Z

You cannot solve this problem easily with a date property. I suggest you create a birthday object schema:
const Birthday = {
name: "Birthday",
properties: {
year: "int",
month: "int",
day: "int"
}
};
and then use it in Student:
const Student = {
name: "Student",
properties: {
// ...
birthday: "Birthday"
}
};
You can now filter Student on birthday.month and birthday.day.

Related

Search for event date falling between two Cloud Firestore timestamps in SwiftUI

Primarily what I’m looking to do, is to pull out documents from my Cloud Firestore when the current date falls between two timestamp fields. I have included simplified code snippets below. Hopefully it makes sense, as I’m a noob.
I have a Cloud Firestore collection named ‘calendar’ with numerous documents in it.
Each document has an event ‘title’ field plus two timestamp fields ‘datebegin’ and ‘dateend’.
struct Calendar: Decodable, Identifiable {
var title: String = ""
var datebegin: Date = Date()
var dateend: Date = Date()
}
I am parsing out the values from each document into event calendar instances:
class Calendars: ObservableObject {
let db = Firestore.firestore()
#Published var calendars = [Calendar]()
init() {
getDatabaseModules()
}
func getDatabaseModules() {
db.collection("calendar")
.getDocuments { snapshot, error in
if error == nil && snapshot != nil {
var calendars = [Calendar]()
for event in snapshot!.documents {
var e = Calendar()
e.title = event["title"] as? String ?? ""
e.datebegin = (event["datebegin"] as? Timestamp)?.dateValue() ?? Date()
e.dateend = (event["dateend"] as? Timestamp)?.dateValue() ?? Date()
calendars.append(e)
}
DispatchQueue.main.async {
self.calendars = calendars
}
}
}
}
And I have been able to pull out the data in my view, so I know that I am able to access it okay:
struct HomeView: View {
#EnvironmentObject var calendars: Calendars
var body: some View {
ForEach(0..<calendars.calendars.count, id: \.self) { events in
Text("\(calendars.calendars[events].title)")
Text("\(calendars.calendars[events].datebegin)")
Text("\(calendars.calendars[events].dateend)”)
}
}
}
Primarily what I’m looking to do, is only pull out only the calendar events when the current date (i.e. now) falls between the datebegin and dateend.
And then I would subsequently sort the resulting list by day ideally (based on the Day of datebegin), so it should end up with something like this (for an example with 9 documents that meet the criteria):
Monday
document2.title
document5.title
Tuesday
document4.title
document9.title
Wednesday
document3.title
document6.title
document7.title
Friday
document1.title
Saturday
Document8.title
Any advice is appreciated and can provide more info as needed.
you could try this approach, using some functions to ...pull out only the calendar events when the current date (i.e. now) falls between the datebegin and dateend... and sorting the results based on time to ...then I would subsequently sort the resulting list by day ideally (based on the Day of datebegin).... Adjust the approach to suit your desired time accuracy, for example, day, weeks ...
Note, it is not a good idea to use the name Calendar for your struct, as Swift already has a Calendar declared.
struct ContentView: View {
#StateObject var model = Calendars()
var body: some View {
HomeView().environmentObject(model)
}
}
struct HomeView: View {
#EnvironmentObject var calendars: Calendars
let now = Date()
var body: some View {
// -- here
List {
ForEach(calendars.allBetween(now).sorted(by: {$0.datebegin < $1.datebegin})) { event in
VStack {
Text("\(event.title)")
Text("\(event.datebegin)")
Text("\(event.dateend)")
}
}
}
}
}
struct Calendar: Decodable, Identifiable {
let id = UUID() // <-- here
var title: String = ""
var datebegin: Date = Date()
var dateend: Date = Date()
// -- here
func isBetween(_ date: Date) -> Bool {
datebegin.timeIntervalSince1970 < date.timeIntervalSince1970
&&
date.timeIntervalSince1970 < dateend.timeIntervalSince1970
}
// alternatively, day comparison
func isBetweenDay(_ date: Date) -> Bool {
!(Foundation.Calendar.current.compare(date, to: datebegin, toGranularity: .day) == .orderedAscending || Foundation.Calendar.current.compare(date, to: dateend, toGranularity: .day) == .orderedDescending)
}
}
class Calendars: ObservableObject {
let db = Firestore.firestore()
#Published var calendars = [Calendar]()
init() {
getDatabaseModules()
}
// -- here
func allBetween(_ date: Date) -> [Calendar] {
calendars.filter{ $0.isBetweenDay(date) } // <-- or $0.isBetween(date)
}
func getDatabaseModules() {
db.collection("calendar")
.getDocuments { snapshot, error in
if error == nil && snapshot != nil {
var calendars = [Calendar]()
for event in snapshot!.documents {
var e = Calendar()
e.title = event["title"] as? String ?? ""
e.datebegin = (event["datebegin"] as? Timestamp)?.dateValue() ?? Date()
e.dateend = (event["dateend"] as? Timestamp)?.dateValue() ?? Date()
calendars.append(e)
}
DispatchQueue.main.async {
self.calendars = calendars
}
}
}
}
}

Output #sys.date_time value to the Sheet

First of all, when I input "Tomorrow noon", the system output "2019-09-21T12:00:00+08:00"(parameter: whattime). When I inputted the word – "Tomorrow noon", the system would convert it into whatime: {"date_time": ""2019-09-21T12:00:00+08:00"}.
Second, there's only time to show it up after inputting a period of data. (you can check this picture I posted).
How do I fix my codes?
function saveDataHandler(agent){
const{
namelist, howmanypeople, whattime, forhere
} = agent.parameters;
const data = [{
Name:namelist,
Number:howmanypeople,
Time:whattime[1],
Forhere:forhere
}];
axios.post('.....it's about API', data);
}
If whattime value is whatime: {"date_time": "2019-09-21T12:00:00+08:00"}, you should access date_time in whatime before sending it.
const{
namelist, howmanypeople, whattime:{"date_time":dt}, forhere
} = agent.parameters;//modified
const data = [{
Name:namelist,
Number:howmanypeople,
Time:dt.toString(),//modified
Forhere:forhere
}];
OR
const{
namelist, howmanypeople, whattime, forhere
} = agent.parameters;
const data = [{
Name:namelist,
Number:howmanypeople,
Time:whattime["date_time"].toString(),//modified
Forhere:forhere
}];
To read:
Working with objects

"Force unwrapping" in Flow?

I have this helper function in my reducer, which has the given state:
type CustomerCollection = { [number]: Customer }
type CustomerState = {
+customers: ?CustomerCollection,
+newItem: ?(Customer | Review),
+searchResults: ?(Customer[]),
+error: ?string,
+isLoading: boolean
};
function customerWithReview(review: Review): Customer {
const id: number = review.customerId;
const oldCustomer: Customer = state.customers[id];
const newReviews: Review[] = [review, ...oldCustomer.reviews];
return Object.assign(oldCustomer, { reviews: newReviews });
}
I get a Flow error on the id of const oldCustomer: Customer = state.customers[id]; saying Cannot get state.customers[id] because an index signature declaring the expected key/value type is missing in null or undefined.
This is happening because of the nullable/optional ?CustomerCollection type of state.customers.
I can silence the error by making sure customers isn't null:
if (state.customers) {
const oldCustomer: Customer = state.customers[id];
const newReviews: Review[] = [review, ...oldCustomer.reviews];
return Object.assign(oldCustomer, { reviews: newReviews });
}
But then the problem just goes up the chain because I don't have anything to return from the function.
I can certainly expand it to:
function customerWithReview(review: Review): Customer {
if (!state.customers) {
return new Customer();
} else {
const id: number = review.customerId;
const oldCustomer: Customer = state.customers[id];
const newReviews: Review[] = [review, ...oldCustomer.reviews];
return Object.assign(oldCustomer, { reviews: newReviews });
}
}
But in actual practice, the action that gets us to this branch of the reducer will never be called if state.customers is null, and we'd never return new Customer() and would have no use for it if we did. state.customers is nullable in order to tell the difference between "we haven't fetched the customers yet (state.customers == null)" and "we've fetched the customers but there are none (state.customers == {}).
It would be a lot easier if I could just assert that state.customers would always exist in these cases, which in Swift I would do with force-unwrapping:
const oldCustomer: Customer = state.customers![id];
Can I do anything like this with Flow?
Or, given that only my GET_CUSTOMERS_FAILURE action would ever deal with state.customers == null, is there some other way to restructure my reducer so that this is a little easier? An entirely separate fetchReducer that is has a nullable customer collection while the rest of the actions fall under a different reducer?
You can use invariant function (Check that it works here):
type Customer = { id: number, reviews: Array<Review> };
type Review = { customerId: number };
type CustomerCollection = { [number]: Customer }
type CustomerState = {
+customers: ?CustomerCollection,
+newItem: ?(Customer | Review),
+searchResults: ?(Customer[]),
+error: ?string,
+isLoading: boolean
};
declare var state: CustomerState;
declare function invariant(): void;
function customerWithReview(review: Review): Customer {
const id: number = review.customerId;
invariant(state.customers, 'No customers and I don\'t know why');
const oldCustomer: Customer = state.customers[id];
const newReviews: Review[] = [review, ...oldCustomer.reviews];
return Object.assign(oldCustomer, { reviews: newReviews });
}
You can implement it somewhere in your project and import when necessary.
You can implement it like this:
export function invariant<T>(value: ?T, falsyErrorMessage: string, errorParams?: Object): void {
if (!value) {
log.error(falsyErrorMessage, errorParams || {});
throw new Error(INVARIANT_ERROR_MESSAGE);
}
}
Unfortunately, the name of the function is hard-coded in flow.
Alternative variant is just to add an if and to throw an error in your customerWithReview function directly.

I want to get the data based on todays date and not based on time (sequelize and sqlite)

list: function(req, res, next){
var body = req.body;
models.BillingHeader.findAll({
where:{
bill_date_and_time: new Date(),
bill_status: {
$and: {
$ne: "C",
}
}
}
}).then(function(BillingHeader) {
res.status(200).send({data: BillingHeader});
});
}
When i am using new Date then its comparing with both date and time and then i get the data ........even if there is a differnce of seconds its showing data = null.Here i want to compare only date and not time and based on todays date i will get the data..........
You can use $like
bill_date_and_time: {
$like: moment().format('YYYY-MM-DD') + '%'
},

ExtJS DateField using datetime format

var todate = new Ext.form.DateField({
format: 'd/m/Y',
fieldLabel: '',
id: 'txtExpireDate',
name: 'txtExpireDate',
width: 150,
allowBlank: false,
value: '',
renderTo: 'divDateExpire'
});
This code to display only date. How to use datetime format?
Thank you
In Ext.Form.DateField we're not able to show time directly when selecting a date in date picker. For that we add listeners:
var dtpIssueDate = new Ext.form.DateField({
listeners: {
select: function(dtpIssueDate, date) {
BindTimeWithDate(date);
}
}
});
//Bind time with date selected in the picker
function BindTimeWithDate(date) {
try {
var currentTime = new Date()
// Get a current hours and add with date.
date.setHours(currentTime.getHours());
// Get a current minutes and add with date.
date.setMinutes(currentTime.getMinutes());
dtDateTimeValue = date.format('dd/MM/yyyy HH:mm');
dtpIssueDate.SetText(dtDateTimeValue);
}
catch (e) {
alert(e.message);
}
}
There is no component in extjs library which can display date & time both. And thus, you cannot use date time format in one. The closest one can get to is with this.
Hope this helps.

Resources