.diff is not a function in Moment.js - javascript

I'm trying to get the difference between two dates, but I'm getting the response: Uncaught TypeError: x.diff is not a function
On other topics I've seen I have to create a moment object, but for as far as I know, I'm doing that.
Code:
function datecheck(){
var y = moment($("#input_pickup_date").val(),"L").format("L");
var x = moment().format("L");
console.log(x.diff(y, 'days'));
}

Via the docs, moment().format() returns a String, so your x and y variables are both Strings. If you need to both do calculations on and display the values, separate them out into different variables:
function datecheck() {
var dateSubmitted = moment($("#input_pickup_date").val(), "L"), //your old x variable
now = moment(), //your old y variable
dateSubmittedDisplay = dateSubmitted.format("L"), //a string representing the submitted date in the format you wanted.
nowDisplay = now.format("L"); //a string representing now in the format you wanted.
console.log(x.diff(y, 'days'));
}

Related

How do I compare a JSON date string to javascript string?

I'm trying to compare two time values, I am creating a new date variable in jS and then passing this down to Memberstack in JSON (this works). I am then calling the data when the page reloads and pulling the value back from Memberstack to compare the dates between the first load and second load.
Here is my code:
// Run timer. //
function runTimer() {
MemberStack.onReady.then(async function(member) {
var metadata = await member.getMetaData() // <------ call the initial date value from Memberstack
if (metadata.startDate != null) {
var initiatedDate = metadata["startDate"]; // <------ the initial date value
var referenceDate = currentDate; // <------ the second date value to compare to
var calcDifference = referenceDate.getTime() - initiatedDate.getTime(); // <------ errors here
var calcDifferenceD = calcDifference / (1000 * 3600 * 24);
alert(calcDifference);
}
})
}
// End run timer. //
When I try to debug this in console I see the following:
When I run initiatedDate.getTime(); on line 83, I'm getting this error:
Uncaught (in promise) TypeError: initiatedDate.getTime is not a function
I need to make lines 81 and 82 match so that I can compare them, can anyone help me compare these two dates?
Right here is the answer to your question.
Your initiatedDate is not an object, but a string, hence .getTime does not exist. So you should convert your string to a Date object.
This is how you can do it:
var initiatedDate = new Date(metadata['startDate'])
And then your initiatedDate will have the .getTime method and there's not going to be an error.

Assign text to variable inside the String

I am saving string into mongoDB with preset variable as
'Current time is ${time}'
After that I am retrieving somewhere else this string and would like to assign value to time
It would look something like this
const time = '15:50'
const response = result //saves string retreived from mongo
res.json({
response: response
})
But that returns 'Current time is ${time}' instead of 'Current time is 15:50'
I am aware that the string should be in `` instead of single quotes for variable to work, not sure though how to implement that as output from mongo
Anyone could point me to correct direction?
An alternative is to pass the string and parameters to a function and reduce over the parameters object:
var str = 'Current time is ${time}';
var params = { time: '13:30' };
function merge(str, params) {
return Object.keys(params).reduce((out, key) => {
return str.replace(`\${${key}}`, params[key]);
}, '');
}
console.log(merge(str, params));
And this is an example of interpolation magic, as mentioned in other answer ;) Note, than even without the evil() ;)
var time = '15:50'
var response = 'Current time is ${time}'
var converted = (_=>(new Function(`return\`${response}\`;`))())()
console.log(converted)
Interpolation is not performed on a string variable that happens to contain a template literal placeholder. In order for interpolation to happen, you must have a literal string in the code, enclosed in back ticks with a placeholder:
let time = '15:50';
let message = `Current time is ${time}`
console.log(message); // "Current time is 15:50"
If you must store strings in your database, you'll have to come up with your own mechanism for interpolating your placeholders.

Why is my custom validation in Angular2 not working

Here are two angular2 custom validations that I wrote, the first one validateAge works, but the second one validateDob does not ... the difference is the validateAge uses the component that I am on and is a text based field, the second one needs to use a Date Entry field and find the difference between today's date and the birthdate to find the actual age and then measure it against the age field. but something is not right ... any ideas
function validateAge(control: FormControl): { [s: string]: boolean } {
if (parseInt(control.value) <= 0) {
return {invalidAge: true};
}
}
function validateDob(control: FormControl): {[s:string]: boolean}{
var today = new Date();
var calcAge = today - control.value;
if (calcAge != parseInt([{age}]) ){
return {invalidDate: true}
}
}
The issue you have here is that your control.value is not a Date object, but rather the string representation.
var today = new Date();
Difference in milliseconds between the current timestamp and the entered value
var diff = today - new Date(control.value);
divide by ms per year and take the floor
var calcAge = Math.floor(diff/ (1000*60*60*24*365)));
Now do whatever comparison you need against the appropriate value. You didn't show us what your age object is so I don't actually know what comparison you're looking for.
if (calcAge < someAgeThreshold) ){
return {invalidDate: true}
} else {
return null;
}
Also note that with custom validation the validator returns no error when you return null and anything with a value is considered to have an error.

Compare dates as strings in typescript

I am trying to compare two dates as strings in typescript. The input I have is as below :-
startWindow = '05/2014'
endWindow = '05/2018'
I need to write a function to check if the start Window is greater than the end Window.
Both the inputs are of string type.
Thanks
You can convert it to a date and then compare them:
function convertDate(d)
{
var parts = d.split('/');
return new Date(parts[1], parts[0]);
}
var start = convertDate('05/2014');
var end = convertDate('05/2018');
alert(start < end);

d3.format thousand separator on variables?

Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);

Categories