I have data in my database that I want to query thats from yesterday
when i do
momentendYest', moment().startOf('day').subtract(1,'day').toDate()
its today 7am? i dont understand
I'm trying to do something like this :
const yesterdayCoins = await Coin.find({
category: {
$regex: new RegExp(fullName, "i"),
},
createdAt: {
$gte: startYest,
$lt: endYest,
},
what can i do to make the date from yesterday at 12am to 11:59pm ?
Something likes works with plain javascript.
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()
const yesterday = new Date(year, month, day-1, 23,59,00)
console.log(yesterday)
We make a date for today, get the year, month and then subtract one from day, then hardcode the time.
I wasn't sure if you wanted at midnight or not. If you do, just skip the time parameters.
Related
I at the moment have the day values as strings. (e.g. "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") but no date.
The days describe opening hours of a shop and I would like to translate these string values dynamically based of the locale set on the shop.
I noticed that JS have the wonderful method Date.prototype.toLocaleDateString() but it doesn't seem like that I can get the localized string without providing a date. How would you go about this?
Have a look at Date.prototype.getDay
// First day of the week depends on the order of this array
const weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const date = new Date();
// get first day of week, and then add the weekday
let day = date.getDate() - date.getDay() + weekdays.indexOf(prompt("Day?", "Monday"));
date.setDate(day)
console.log(date.toString());
You can create a dummy date based on the weekday, choosing the year and month such that a day value of 0 matches a Sunday (yes, you can specify the 0th day too).
Then you can use toLocaleDateString with the date to ask for the translated weekday string.
(I also invoked an Intl.DateTimeFormatter here to get the user's default locale, because we cannot specify an options object without also specifying a locale.)
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
function translateWeekday (weekdayString) {
const weekdayIndex = WEEKDAYS.indexOf(weekdayString.toLowerCase())
if (weekdayIndex < 0) throw new Error(`Unknown weekday "${weekdayString}"`)
const dummyDate = new Date(2001, 0, weekdayIndex)
const locale = new Intl.DateTimeFormat().resolvedOptions().locale
return dummyDate.toLocaleDateString(locale, { weekday: 'long' })
}
On my machine with German locale, translateWeekday('Wednesday') returns 'Mittwoch' for example.
You can use the Date() perhaps
// current date
let date = new Date();
Additionally, we can get a day of week:
getDay()
Get the day of week, from 0 (Sunday) to 6 (Saturday).
When using the Date() method you can also check for year, month, day and time. Maybe if you want to check so that it´s not on christmas day or after closing hours etc. Should work fine!
Methods:
getFullYear()
Get the year (4 digits)
getMonth()
Get the month, from 0 to 11.
getDate()
Get the day of month, from 1 to 31, the name of the method does look a little bit strange.
getHours(), getMinutes(), getSeconds(), getMilliseconds()
Get the corresponding time components.
Just create a new date object pointing to any Monday, then add days consecutively while calling date.ToLocaleDateString(LOC, {weekday: 'long'}), replace LOC with any locale you wish to use, to define in which language you'd like to get the week names.
function listDayNames(elem, locale)
{
let e = document.getElementById(elem);
let date = new Date('2022/08/22');
for(let i=0;i<=6;i++) {
e.innerHTML += date.toLocaleDateString(locale, { weekday: 'long' }) + '<br>';
date.setDate(date.getDate() + 1);
}
e.innerHTML += '<hr>';
}
let date = new Date();
listDayNames('days', 'en-US');
listDayNames('days', 'de-DE');
<p id="days"></p>
I realized there is a strange behavior when using a where() clause on a Timestamp field in a Firestore query(). I'm using the modular version 9 of Firebase.
Maybe someone has an explanation for that.
So here's the data I see in the Firebase/Firestore console:
Assuming, that today is the 27th December 2021, I want to query all documents for this day - in this case, only the one document from above.
I would use the following query (i.e. everything after today at midnight and before tomorrow at midnight):
const today = new Date(new Date().setHours(0,0,0));
const tomorrow = new Date(new Date(today).setDate(today.getDate() + 1));
const docQuery = query(collection(getFirestore(firebaseApp), 'ticks1'),
where('date', '>=', today),
where('date', '<', tomorrow)
)
const querySnapshot = await getDocs(docQuery)
console.log('documents count:', querySnapshot.docs.length)
But: this returns no results!
documents count: 0
Instead, if I change the value in the database to 12:00:01 AM (see below), it works and I retrieve the expected document.
documents count: 1
Can somebody explain this behavior - or is it a bug in the Firestore implementation?
Alternative solution I'm using at the moment
Instead of the range [today 12:00:00 AM, tomorrow 12:00:00 AM)
, I'm using this date range now: (yesterday 11:59:59 PM, today 11:59:59 PM]
const now = new Date()
const dateFrom = new Date(new Date(new Date(now).setDate(now.getDate() - 1)).setHours(23,59,59))
const dateTo = new Date(new Date(dateFrom).setDate(dateFrom.getDate() + 1));
const docQuery = query(collection(getFirestore(firebaseApp), 'ticks1'),
where('date', '>', dateFrom),
where('date', '<=', dateTo)
)
const querySnapshot = await getDocs(docQuery)
console.log('documents count:', querySnapshot.docs.length)
documents count: 1
At least this makes sense, even though it looks a bit odd.
I have a form that sends the value of year and months from an input and then while sending the value to the server I am converting that values to ISO string like that:
const toIsoString = (year, month, day) => moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
And then in the values I am using it like this.
StartDate: toIsoString(data.StartYear, parseInt(data.StartMonth, 10), 1),
In that case It is sending the value like this:
startDate: "2021-01-01T00:00:00"
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.Thanks...
Does anybody know why the Time period is being ignored and how can I also send the time period with the year, month and date values.Any helps would be highly appreciated.
The time isn't ignored. In the function:
const toIsoString = (year, month, day) =>
moment(new Date(year, month - 1, day)).toISOString(true).split('.')[0];
the values for hour, minute, second and millisecond are omitted so they default to 0. What time are you expecting?
If you want the current local time added to the date, then create a date and set the year, month and day to the required values without modifying the time (though I don't know why you'd want to do that).
Rather than creating a string that you then need to further process, tell moment.js the format you want:
function toIsoString (year, month, day) {
return moment(new Date().setFullYear(year, month-1, day)).format('YYYY-MM-DD HH:mm:ss');
}
console.log(toIsoString('2021','1','1'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
You can also do that without a library, see How to format a JavaScript date, e.g.:
function formatDate(year, month, date) {
let z = n => (n<10?'0':'') + Number(n);
return `${year}-${z(month)}-${z(date)} ${
new Date().toLocaleString('en',{
hour12:false,
hour:'2-digit',
minute:'2-digit',
second:'2-digit'})
}`;
}
console.log(formatDate('2021','1','01'))
Its because you are only setting year, month and date while creating moment object. You are not setting time
You should do something like
const toIsoString = (year, month, day) => {
const currDate = moment(new Date());
currDate.year(year);
currDate.month(month - 1);
currDate.date(day);
return currDate.toISOString(true).split('.')[0];
}
Or simply use set function
const toIsoString = (year, month, day) => {
const currDate = moment(new Date());
currDate.set({
'year': year,
'month': (month - 1),
'date': day
});
return currDate.toISOString(true).split('.')[0];
}
I submit a date to nodejs server in the following format
2018-11-02T00:36:00+05:30 // Actual time is 12:36AM
When I check the document in the database (studio 3T) the format looks like
2018-11-01T19:06:00.000Z // minus 5.30 hours from the actual time 12:36AM
Now the situation is that i have to search all the documents by starting and ending of the day for any given date.
How can I pull all the documents for the date 2018-11-02
If I query to find the documents by start time and end time of 2018-11-02 For Example with moment js start and end day:
I get today as 2018-11-01T18:30:00.000Z and tomorrow as 2018-11-01T23:59:59.999Z
What I tried
const today = req.body.date;
const tomorrow = moment(today).endOf('day').toISOString();
"startDate" : { "$gte": new Date(today), "$lt": new Date(tomorrow) }
// today is 2018-11-01T18:30:00.000Z tomorrow is 2018-11-01T23:59:59.999Z
It gives an incorrect end date.
I have just add one day to the start day of the today in ISO Format
const today = moment(new Date(req.body.date)).startOf('day');
const tomorrow = moment(new Date(today)).add(1, 'days').toISOString();
"startDate" : { "$gte": new Date(today), "$lt": new Date(tomorrow) }
I tried to get Date from datestring but it's not wokring properly.
var time = new Date('2017-12-26T02:12:00')
But when I called time.getHours() it returns 12.
I am not sure what I am doing wrong.
Use below code to get day, month and year.
var date = new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
today = day+"-"+month+"-"+year;
You can change the format of date as per your requirement.
Adding below code fixed the problem
time.setMinutes(time.getMinutes() + time.getTimezoneOffset());
:)