Why does moment not recognize the .add method? - javascript

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)

Related

Regex using array.filter in javascript

I'm trying to use a regular expression to filter the name column in a csv file that has be put into an object array. Everything works fine if I type the exact value.
values I want "king" to match are below:
kingkong, king kong, king-kong, king_kong, king11, kongking, kong-king, kong_king, kong king, 11king
I've tried using filter and find methods but I want to use filter to return multiple values if they exist. I have tried the following regex but can't figure out the proper sytax if it is even correct.
const CSVToJSON = require('csvtojson');
const user = "king";
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"]== /\bking.*/g));
})
You can use the following approach.
const CSVToJSON = require('csvtojson');
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"].match(/king/g)));
});
return statement could be something like
return ((/king/g).test(v["name"]));
OR
return ((v["name"].match(/king/g)));
Both should work
However, your sample patterns show that king might stand either at the beginning or at the end of the target (bot can't have both prefix and suffix). If I am right, that means you don't need regex for that.
const CSVToJSON = require('csvtojson');
const user = "king";
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter((v, i) => v.startsWith(user) || v.endsWith(user))
/*rest of the code */
});
If king can stand anywhere, you can simply use includes instead.
This is what worked, I'm totally new to JavaScript:
const user = args;
var regex = new RegExp(user, "g");
CSVToJSON().fromFile("./locations.csv").then(source => {
var found = source.filter(function(v, i){
return ((v["name"].match(regex)));
})

Moment date is rolling back to previous month

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.

Transform array into newline separated string using map.reduce?

I think it should be possible to use map.reduce to transform an array into newline separated string. But for some reason it is not working. What am I doing wrong
copyLicenseCodesToClipboard = () => {
// tslint:disable-next-line:no-any
const licenseCodes = this.props.generateLicenseCodes.reduce((accumulator: any, element: LicenseCode) =>
accumulator.concat(element.code).concat('\n')
);
copyToClipboard(JSON.stringify(licenseCodes));
}
Uncaught TypeError: accumulator.concat is not a function
You can also use map and join, which seems to be more intuitive in this case.
const licenseCodes = this.props.generateLicenseCodes.map((element)=>{return element.code;}).join("\n");

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.

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