Moment date is rolling back to previous month - javascript

I have a datetime coming from my api as 2018-09-01T00:00:00.000Z. This is frame.scandate.
I have another date which is generated within my program as 2018-09. This is just scandate. These could be for any year/month combo, I am just giving examples.
My code looks like
this.allStations.forEach(station => {
station.frames.forEach(frame => {
if(moment(frame.scandate).isSame(moment(scandate), 'month')){
total+=frame.framesTotal;
}
})
This will match the previous frame.scandate with the the current scandate.
This:
scandate = '2018-09';\
frame.scandate = '2018-09-01T00:00:00.000Z';
console.log(moment(scandate).format('YYYY-MM'));
console.log(moment(frame.scandate).format('YYYY-MM'));
will output this:
2018-09
2018-08
I fixed the problem by doing this:
this.allStations.forEach(station => {
station.frames.forEach(frame => {
if(moment(frame.scandate).add(1, 'minute').isSame(moment(scandate), 'month')){
total+=frame.framesTotal;
}
})
.add(1, 'minute') being the key change here.
Is this because the frame.scandate value has the 00:00:00Z time value? Any explanation would be greatly appreciated.

There's probably something going on with the timezones.
This script, ran in Spain
var moment = require('moment'); // This is because I've tested it in a nodejs environment
var scandate = '2018-09';
var result = moment(scandate);
console.log(moment(result).format('YYYY-MM-DD'))
Outputs 2018-09-01
We could get around this by initializing frame.scandate like so:
frame.scandate = moment.utc('2018-09-01T00:00:00.000Z');
With moment.utc() instead of just moment() the output expectations are met.

Related

Build nested Object/Array with jquery

I'm trying to build a javascript object from the inputs of a dynamic form. This is what I'm trying to do:
fieldTickets = [];
thisWeek = randomDateOnSunday;
weekDay = randomWeekDayWithinTheWeek;
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({name: fieldTechName});
As you can see, I have some keys that are dynamic variables and some that are defined ('days' and 'fieldTechs' are always the same, but the week and weekday will change). Unfortunately every time I try to run this, even on fiddles, it gives me Cannot read properties of undefined (reading 'days') as an error. I've been dealing with this for hours and can't figure it out.
How does one build a nested array/object with dynamic keys?
i thought that it would create it automatically if it didn't exist by
using that syntax...obviously I'm wrong but is there another shorter
way than a ton of if exists statements?
JavaScript will not create it automatically, but can do it without if, try something like below
const thisWeek = '12'; //randomDateOnSunday;
const weekDay = 'Sunday'; // randomWeekDayWithinTheWeek;
fieldTickets = {
[thisWeek]: {
days: {
[weekDay]: {
fieldTechs: []
}
}
}
};
console.log('fieldTickets:', fieldTickets);
// pushing
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({
name: "Hello"
});
// pushing again
fieldTickets[thisWeek]['days'][weekDay]['fieldTechs'].push({
name: "World"
});
console.log('fieldTickets 2:', fieldTickets);

How to remove this error message: "TypeError: Cannot read property 'seconds' of undefined"?

I would like to receive a boost as I have been stuck on this issue for quite some time. Thank you very much for your precious time.
Goal :
I would like to solve a problem. The problem is this error message in the console:
Results:
I am using firestore and the timestamp looks like this:
Timestamp (seconds = 1620748267, nanoseconds = 746000000)
I know how to display the value I want but cannot remove this error .. I tried to transform the timestamp into a javascript date by looking at the firebase documentation here but it just replaces the error .. Every thing I put after the timestamp turns into an error in the console..
My code :
<small class="text-muted"> {{ dateTime(job) }}</small>
My function dateTime :
dateTime(job) {
const createdAt = job.createdAt;
const d = new Date(createdAt.seconds * 1000);
const currDate = d.getDate();
const currMonth = d.getMonth() + 1;
const currYear = d.getFullYear();
const dateTime = `${currDate}-${currMonth}-${currYear}`;
return dateTime;
}
So, would you know where the problem is coming from? If you are missing anything, please let me know, thank you!
Instead of creating your own Date object from the Firestore Timestamp, try using the Firestore Timestamp's toDate method to create a Date instead.
const d = createdAt.toDate()
I suspect job is initially an empty object and asynchronously updated (after an API call) to include createdAt. Your template likely renders that markup unconditionally before this update occurs, at which point job.createdAt is undefined.
A simple fix is to check job.createdAt before trying to use it:
dateTime(job) {
const createdAt = job.createdAt;
if (!createdAt) return ''
//...
}
Alternatively, you could initialize job to null, and conditionally render that date markup, assuming job.createdAt will exist when job is populated:
<template>
<small class="text-muted" v-if="job"> {{ dateTime(job) }}</small>
</template>
<script>
export default {
data() {
return {
job: null, // asynchronously updated by API call
}
}
}
</script>

Return most recent time in series of creationTimes

Not entirely sure how I word the question but my problem is Im doing an api call that returns a bunch of messages that have a creation time, now what I want to do is only return the latest creationTime for the messages with the same date so say If I have 30 messages on the 15/03/2018 I want to grab the latest time, and discard the rest.. and do that for each set of messages with the same date
So what Ive done so far is..
using lodash I have gotten all the messages, filtered out all the ones with a certain type, and I have ordered them by creationTime so the latest being at the top and going down.. now my question is how can I then make an array of the latest times for each date??
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
console.log(loginFiltered);
});
any help would be appreciated!
Thanks
Use .map(...) to get at array of only the latest creationTime:
this._activityServiceProxy.getAllItems(start, end).subscribe(result => {
// this.messages = result;
// console.log(result);
let loginUnfiltered = _.filter(result, {'title': 'LOGIN'});
let loginFiltered = _.orderBy(loginUnfiltered, {'creationTime': 'desc'});
const creationTimes = loginFiltered.map(l => l.creationTime);
console.log(creationTimes);
const latestTime = creationTimes[0];
console.log(latestTime);
});
You can use Underscore's groupBy function to achieve this:
const groups = _.groupBy(loginFiltered, (login) => {
const asDate = new Date(login.creationTime);
asDate.setHours(0, 0, 0, 0);
return asDate;
});
Object.keys(groups).forEach((key) => {
console.log(groups[key][0]);
});
You group by the creationDate property but remove the time component so all days get grouped together. You then loop through the result and just take the first entry per day.
Note that this assumes your creationTime property is a string, as it came from an API. If it's already a date, you don't need the new Date line.

Why does moment not recognize the .add method?

moment=require('moment');
const now= moment();
const dateFormat1 = 'MMDDYYYY';
this.todaysdate = () => (`${now.format(dateFormat1)}`);
this.futuredate= () => (`${now.format(dateFormat1).add('days', 5)}`);
When I run this, I get that add is not a recognizable function. numerical Begindate works fine.
A string, which is returned from format, doesn't have add on it's prototype. Try to add on the moment instead
now.add('days', 5).format(dateFormat1)

Console.log this WIx Code function

How do i log this successfully please. When i print, it prints only the syntax and not the values. I would also want to display it as text.
$w("#datePicker1").onChange( (onChange, $w) => {
let chosenDate = new Date($w("#datePicker1").value);
let date1 =chosenDate.getDate();
return date1;
});
$w("#datePicker2").onChange( (onChange, $w) => {
let chosenDate = new Date($w("#datePicker2").value);
let date2 = chosenDate.getDate();
return date2;
});
//printing everthing instead of values
console.log($w("#datePicker1").onChange);
console.log($w("#datePicker2").onChange);
this is because you're printing the function's actual code, as described in Function.prototype.toString().
$('#some_input').onChange function is an event handler and returning the object of the triggered element (see WixCode DatePicker API Docs)
You didn't mentioned what you wish to do with the date value, so I'm guessing that you may be wanted to put it in your database to update a specific item (the current item the dataset points to). Assuming this is what you're trying to do, here is a code to help:
$w("#datePicker1").onChange((event, $w) => {
let date = event.target.value;
// maybe do some manipulation here on the saved value
$('#dataset1').setFieldValue('last_modified_date', date)
});
Hope this could help,
Cheers!

Categories

Resources