How to parse array of date string into Dates in moment - javascript

I've a array of dates in a string format.
I wanted to parse the array of dates and pass that new date value into addDates
i tied .format('YYYY-MM-DD'), but not working its give an error Conversion from "undefined" format not allowed on jQuery.multiDatesPicker. Please help
var newDateArray: any[];
"Dates": [
"2018-01-01",
"2018-01-03",
"2018-01-05"
]
for(let i=0; i<= this.newDateArray.length; i++) {
let date = moment(i).format('YYYY-MM-DD');
this.newDateArray.push(i)
}
$(this.eInput).multiDatesPicker({
addDates: [this.newDateArray],
dateFormat: "dd/mm/yy"
});

There are a few issues in your code. Your dates declaration isn't proper javascript, although I'm assuming you copied this from within an object or something. You are also iterating over the empty list rather than your date list and only passing the index in to moment. Change your for loop to this:
var newDateArray: any[];
dates: [
"2018-01-01",
"2018-01-03",
"2018-01-05"
]
// iterate over the dates list from above
for(let i = 0; i <= dates.length; i++) {
// pass the date at index i into moment
let date = moment(dates[i]).format('YYYY-MM-DD');
console.log("date", date);
// add this new date to the newDateArray
this.newDateArray.push(date)
console.log("newDateArray", this.newDateArray);
}

Related

How to do execute a query loop inside of another query loop

so my question is, how i can achieve this: I have an array of dates and an array of locations, i want to iterate the array of dates, and for each date, execute some query's, them iterate the whole array of locations doing an query for each item and them return an JSON response with the data.
P.S. I am using TypeOrm and i am also novice
If you've got two arrays, and you want to loop one inside of the other, then... just do that.
var locations = ['Paris','St Louis','Moscow'];
var dates = ['wednesday', 'thursday', 'friday'];
async function run(locations, dates) {
let results = [];
for (let location of locations) {
for (let date of dates) {
console.log(`${location} - ${date}`);
const newResults = await query(location, date);
results = results.concat(newResults);
}
}
return results;
}
run(locations, dates);
edited to include async query example

Dynamic variable in $in mongoose

I have following variables. (I am using this query in mongoose, node )
var splitDates=currentDate.split('-');//2019-12-09
currentDate=splitDates[0]+splitDates[1]+splitDates[2] //returns 20191209
previousDate= splitDates[0]+splitDates[1]+splitDates[2]-1;
I want it in the mongoDB query:
{ batchRef: { $in: [/20191209/, /20191210/] } }, // this is static values and works.
{ batchRef: { $in: ['/'+previousDate+'/','/'+currentDate+'/'] } }, // this doesnt work!
am I missing something?
any help would be appreciated.
This looks like a javascript date transformation question.
You can use the following code to get a string array for a given date and previous date to be used in $in query.
const inputDateString = "2019-12-09";
const currentDate = new Date(inputDateString);
const previousDate = new Date(inputDateString);
previousDate.setDate(currentDate.getDate() - 1);
let inArray = [];
inArray.push(inputDateString.split("-").join(""));
inArray.push(
previousDate
.toISOString()
.slice(0, 10)
.split("-")
.join("")
);
console.log(inArray);
inArray will have these 2 items:
[ '20191209', '20191208' ]
Now we can use this in the query like this:
{ batchRef: { $in: inArray } }
Please not that I assumed that inputDateString is always in this format with 10 characters, like 2019-01-31 or 2019-01-01

How to push properties to an array within an object within an array via looping?

I am creating a small Angular application that operates like a scheduler.
It allows users to give a Name, Start and End dates and check a boolean checkbox via a form.
My problem is I am trying to push the names of each user entry to specific dates in the array, e.g. 26/01/2019 will have the following names: "James", "Mark", "Luke" etc. all on the same day, depending on user entry via the form.
Within my loops, I am pushing a new object for each date within a date range, but cannot figure out a way to push the names to the string array within each date object.
I have tried to push the value to the array within another push, which keeps giving me errors.
I notice that if I set the value of the name field within the loop to "[value]" it doesn't error for some reason, not sure why.
After the loops have finished, I want to alert the resulting object array, but when I write the code to do so, I get an alert of "undefined". are the values not saving to the array?
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { IPreferences } from '../ipreferences';
import { DatePipe } from '#angular/common';
import * as moment from 'moment';
#Component({
selector: 'app-customer-form',
templateUrl: './customer-form.component.html',
styleUrls: ['./customer-form.component.css']
})
export class CustomerFormComponent implements OnInit {
title = 'Preference Form';
preferences: IPreferences;
dateObj: { }; // to be array of Date objects containing Name sub-arrays
nameArray: string[];
date = new Date();
constructor(public datepipe: DatePipe) {
this.preferences = {
name: '',
dateFrom: null,
dateTo: null,
everyday: null
}
}
getDates(startDate, endDate){
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
}
savePreferences(form): void {
var savedName:string = this.preferences.name;
var formatDateFrom:string = moment(this.preferences.dateFrom).format("YYYY-MM-DD");
var formatDateTo:string = moment(this.preferences.dateTo).format("YYYY-MM-DD");
var savedEveryday:Boolean = this.preferences.everyday;
var savedDateFrom:Date = new Date(formatDateFrom);
var savedDateTo:Date = new Date(formatDateTo);
var dateRange = this.getDates(savedDateFrom, savedDateTo);
if(!!savedEveryday){
for(var i = Number(savedDateFrom); i <= Number(moment(savedDateFrom).format("YYYY-MM-DD") + 90); i++){ // 90 and not infinite as due to time constraints i intended to print
// the first 90 dates regardless of scenario, so if a user selected to receive marketing info daily it would of "appeared" to be daily
this.nameArray.push(savedName) // pushing name strings to nameArray
}
}
if(!savedEveryday) {
dateRange.forEach(date => {
this.nameArray.push(savedName) // pushing name strings to nameArray
})
this.dateObj[Number(this.date)] = {
name: this.nameArray // attempting to set name property of objects in array to nameArray strings (2d array)
}
}
alert(this.nameArray.length); // attempting to test by having a pop up of the object array (Dates) with their corresponding names returned
}
Actual results are an alert of "undefined".
I am expecting to see an alert of objects within an array. Each object having a different date, and arrays of different names within each object.
I was able to execute this code.
let dateObj = {};
let name_array = []; // this is a temporary storage for the name;
let date = new Date(); // this the date object that you are going to use as a key
name_array.push("James");
name_array.push("Mark");
name_array.push("Luke");
print(name_array);
/*Below is the basic declaration of the key value pair in JavaScript*/
dateObj[date] = {
name: name_array
};
/*if you want to retrieve content that is associated with the key(DATE) object use*/
dateObj[date].name;
print(dateObj[date].name);
Can you post your code i can check and what went wrong
You can put the code in here: https://rextester.com/l/js_online_compiler and test
The way i understood you question is that:- you want to add multiple names to the same date, and at the same time you want to add new dates.
You can actually do that using key value pair concept.
Basic structure of key value pair is you need to create an empty object.
let a = {};
and use this object to enter the values.
For example: in the scenario you mentioned:
let dateObj = {};
let name_array =[]; // this is a temporary storage for the name;
let date = new Date(); // this the date object that you are going to use as a key
name_array.push("James");
name_array.push("Mark");
name_array.push("Luke");
/*Below is the basic declaration of the key value pair in JavaScript*/
dateObj[date] = {
name: name_array
}
/*if you want to retrieve content that is associated with the key(DATE) object use*/
dateObj[date].name // this will return all the name associated with that date object(key)
If you want to print all the contents use the for loop to iterate through the DATE (key value pair).
One more advantage of this method is that if you want to enter a name
to an existing key you do not have to iterate through all the key
value pair.
you can just use the code
dateObj[date] = {
name: name_array
}
If the key exist you can perform update if not a new key value pair is created. By this way you can avoid iterating though unnecessarily Its a more efficient way than others at-least to my knowledge

forEach unexpected token adding new property to existing array

I want to add a new proeprrty call total_days calculate using date_from and date_to but my forEach got an expected token error.
let applicants = [{
date_from: '2017-05-05',
date_to: '2017-05-10'
},{
date_from: '2017-05-08',
date_to: '2017-05-12'
}]
calculateDays = applicants.forEach(obj =>
applicants['total_days'] = (obj.date_from).diff(obj.date_to, 'days')+1;
)
No clue what's wrong here.
You didn't exactly clarify what you wanted but I tried to take a guess by your code.
My guess is that you wanted to create a new array of applicants from the old array of applicants but in the new array, you wanted to add a property to each object in that array that is the difference in days of the two dates.
To do so, you can use Array.prototype.map to map each item from your array to a new array.
I'm also using Object.assign to clone each object so that the original array is unmodified.
I'm also parsing the date strings into number. The parsed number is the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC. If I take the difference of the two numbers and divide that be the millisecondsInADay then I'll get how many days elapsed in between.
The result is then stored into a new array calculateDays.
Let me know if you need more clarification.
let applicants = [{
date_from: '2017-05-05',
date_to: '2017-05-10'
}, {
date_from: '2017-05-08',
date_to: '2017-05-12'
}]
const millisecondsInADay = 1000 * 60 * 60 * 24;
const calculateDays = applicants.map(obj => Object.assign({}, obj, {
total_days: ((
Date.parse(obj.date_to) - Date.parse(obj.date_from)
) / millisecondsInADay) + ' days'
}));
console.log(calculateDays);
Assuming you want to add a new property to all objects, you could use obj as variable with a new property.
applicants.forEach(obj => obj.total_days = obj.date_from.diff(obj.date_to, 'days') + 1);
// ^^^

add items into two arrays (future and past dates) based on date

I am trying to find a way to sort posts into two arrays: upcoming and current (upcoming posts are in the future and current have already been posted).
All posts have a scheduledPubDate that is a date string in the format YYYY-MM-DDT00:00:00. and todays date has to be a Date object as it will need to stay relevent (I am using moment())
Is it possible to compare these two different things without having to use a .split and compare the month / day /year separately
angular.forEach(data.items, function (key, index) {
if (moment(key.scheduledPubDate) > moment()) {
$scope.upcomingPosts.push(item[index]);
} else if (moment(key.scheduledPubDate) <= moment()) {
$scope.currentPosts.push(item[index]);
};
});
Presumably you want the string treated as UTC, a simple parser for that is:
// Expected format YYYY-MM-DDT00:00:00
function parseUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
Note that this doesn't allow for invalid dates. If needed, an extra line if code is required. So now you can do:
if (parseUTC(key.scheduledPubDate) > new Date()) // or Date.now()
You really don't need moment.js for this.
JavaScript's built-in Date object will help you here.
var date = Date.parse('2014-01-21T12:45:13');
date < Date.now() // true
For the purpose of an example, let's assume items is an array of posts:
var items = [{
scheduledPubDate: '2014-01-21T12:45:13'
// ...other keys here
}, {
scheduledPubDate: '2017-03-01T15:21:00'
} // ...and so on
];
Then a reduce operation over items can categorize the posts:
var posts = items.reduce(function (memo, item) {
memo[Date.parse(item.scheduledPubDate) <= Date.now() ? 'current' : 'upcoming'].push(item);
return memo;
}, { current: [], upcoming: [] });
Now posts.current will contain an array of all posts from items whose scheduledPubDate is before the current date, and posts.upcoming will contain an array of all scheduled posts.
Edited to use Date.parse, to avoid unreliable behavior pointed out by RobG. This requires that all dates be in the YYYY-MM-DDT00:00:00 format you specified; if that is not the case, another solution will be required.
You have to specify the date format of the string
var format = "YYYY-MM-DDT00:00:00";
angular.forEach(data.items, function (key, index) {
if (moment(key.scheduledPubDate, format) > moment()) {
$scope.upcomingPosts.push(item[index]);
} else if (moment(key.scheduledPubDate, format) <= moment()) {
$scope.currentPosts.push(item[index]);
};
});
Working example (See the console.log): http://jsbin.com/fejaxiguce/1/edit?html,output
First create an array of elements, in any order, and then use the .sort() method.
http://www.w3schools.com/jsref/jsref_sort.asp
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Just substitute the above logic with your own. a and b above can be objects.

Categories