date.toLocaleDateString is not a function - javascript

Have simple function which returns an error:
ERROR: date.toLocaleDateString is not a function
TypeError: date.toLocaleDateString is not a function
at FormatTime (../Src/rootdialog.js:87:58)
Function definition:
function FormatTime(time, prefix = "") {
var date = Date.parse(time);
return ((typeof time != "undefined") ? prefix + date.toLocaleDateString() : "");
}
Function receives Date object as input however even explicit conversion to Date with Date.parse() does not help. Using Node.js 8.x. Any solution?
P.S. Issue was caused by BotBuilder architecture.

Date.parse returns a number. You are looking for new Date. Or, if time already is a Date instance, just use time.toLocaleDateString() (and make sure it really is in every call to the function)!
function formatTime(time, prefix = "") {
return typeof time == "object" ? prefix + time.toLocaleDateString() : "";
}

You can use
new Date(date).toLocaleDateString();

Got this error in a React app, solved it like this:
{ (item.created instanceof Date) ? item.created.toLocaleDateString() : new Date(item.created).toLocaleDateString() }

You're most likely getting NaN as the result of your Date.parse(time) call.
Check the MDN article on Date.parse for the types of input strings it accepts if you think your time argument should be valid.
You may want to modify your return statement so it's checking for failed parses instead of just undefined, e.g.:
function FormatTime(time, prefix = "") {
var date = Date.parse(time); // returns NaN if it can't parse
return Number.isNaN(date) ? "" : prefix + date.toLocaleDateString();
}

function(ng-model_Name,ng-model_Name) {
var fromdate = new Date($scope.ng-model_Name.from.toLocaleDateString());
var todate = new Date($scope.ng-model_Name.to.toLocaleDateString());
return $scope.variable= asign;
}

Related

Check if date is valid in js

In my app, I am using ReactTimeAgo to display the date a message was sent, but when the user sends a message, I get .toDate() is not a function.
But if I reload the page after receiving the error, it will work fine.
Is there a way that if .toDate() is not a function I just return blank?
For example,
{msg.sent.toDate()?<ReactTimeAgo date={msg.sent.toDate()}/>:''}
But this doesn't work.
typeof message.sent.toDate !== "function" ? "" : message.sent.toDate()
To check if an object is a valid date object, you can check if the object has date methods or not:
const date1 = new Date()
console.log(typeof date1.getMonth === 'function')
const date2 = {
a: 1
}
console.log(typeof date2.getMonth === 'function')
Try optional chaining operator:
date={msg.sent?.toDate()}

How can I check if a date is greater than the other?

I have 2 dates. Both are in yyyy-mm-dd format. I applied a simple check that if
if ('2017-01-15' > '2016-12-15') {
return true;
} else {
return false;
}
But it is giving me a syntax error. What should I do?
Given the format of the date string and your code structure, what you have should be working. If you're getting an error, check that it's coming from the section of code you've shown in your question.
That being said, you can improve the code by changing the strings to Date objects before comparing them. You can also shorten the code by just returning the result of the comparison. Try this:
function dateComparison() {
return new Date('2017-01-15') > new Date('2016-12-15');
}
console.log(dateComparison());
As per the MDN
The return statement ends function execution and specifies a value to be returned to the function caller.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
So you must be getting this error if you are not using the if condition within a function.
Operators like ==, !=, ===, and !== require you to use date.getTime() like this:
var x = new Date('2017-01-15');
var y = new Date('2016-12-15');
var same = x.getTime() === y.getTime();
var notSame = x.getTime() !== y.getTime();
You could convert them to Date objects and then compare.
var dateStrA = "2017-01-15 00:00:00";
var dateStrB = "2016-12-15 00:00:00";
if (new Date(dateStrA) > new Date(dateStrB))
{
...
}
else
{
...
}
Comparing using equals, such as === will not work on Date objects. You can also use Date.compare()
You can use the moment.js library to help you achieve it:
return moment('2017-01-15').format('YYYY-MM-DD') > moment('2016-12-15').format('YYYY-MM-DD');
Try this...worked for me.
var startDate = "2019-03-23";
var endDate = "2019-03-24";
if(Date.parse(endDate) >= Date.parse(startDate)) {
console.log('endDate is greater');
} else {
console.log('startDate is greater');
}
You can try this
if(d1.getTime()>d2.getTime())

Jquery Functions does not work on function parameter

I have a jquery function which receives a parameter from it callers. Calling split() on the parameter throws error. Here is the function
function formatNairaCurrency(value) {
var formatedWithoutNaira;
var formattedAmount
//check if value is in kobo format
var splittedValue = value.split(".");//Throws error
if (splittedValue.length === 2) {
formatedWithoutNaira = isNaN(splittedValue[0]) ? "" : splittedValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + splittedValue[1];
} else {
formatedWithoutNaira = isNaN(value) ? "" : value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + ".00";
}
return formattedAmount;}
The call var splittedValue = value.split("."); throws the error value.split is not a function
What am I missing?
I am calling this in a .cshtml file. This works in another function even on the same .js file. The difference is that the value was not a parameter but a value from a text box.
Your help is greatly appreciated.
If i understand your intention correctly you are trying to use split for string. Your error could be caused by the fact that value is not string. You need to debug or throw to console 'value'.
Edit: For example if
value is null, or value is undefinded this would most definitely cause your error. Testing for those conditions:
(value === null)
(typeof value === 'undefined')
If your value is number - that would cause error too. You need to cast number to string first. You can do it by
var valueAsString = value.toString();
valueAsString.split('.');

Checking if any given string is a valid date

Does anyone know of any way to check if strings are valid dates? I'm trying to block against invalid dates, while not forcing any kind of date format. Basically here's the problem:
!!Date.parse('hello 1') === true
Javascript can figure out a date from that string, therefore, it's a date. I'd rather it not be. Anyone?
How close would stripping out spaces around words get you? It at least weeds out "hello 1" and such.
Date.parse('hello 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // NaN
Date.parse('jan 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // Valid
[update]
Ok, so we'll just replace any non-alphanumerics that fall between a letter and a number:
replace(/([a-z])\W+(\d)/ig, "$1$2")
Since you're using moment.js, try using parsingFlags():
var m = moment("hello 1", ["YYYY/MM/DD"]).parsingFlags();
if (!m.score && !m.empty) {
// valid
}
It's the metrics used for isValid() and you can use them to make a stricter validation function.
Note: You can specify the other formats to support in the second argument's array.
Some other properties returned by parsingFlags() that might be of interest are the following:
m.unusedInput - Ex. ["hello "]
m.unusedTokens - Ex. ["MM", "DD"]
Use this function to check date
function isDate(s)
{
if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
return false;
s = s.replace(/[\-|\.|_]/g, "/");
var dt = new Date(Date.parse(s));
var arrDateParts = s.split("/");
return (
dt.getMonth() == arrDateParts[0]-1 &&
dt.getDate() == arrDateParts[1] &&
dt.getFullYear() == arrDateParts[2]
);
}
console.log(isDate("abc 1")); // Will give false
Working Fiddle
It would be ok if you check for several types of dates?
kind of this for narrow the permited dates:
if( givenDate.match(/\d\d\/\d\d\/\d\d\d\d/)
|| givenDate.match(/\w*? \d{1,2} \d{4}/)
|| givenDate.match(anotherFormatToMatch) )
UPDATED
Or, althougt it restrict characters, you coud use something like this:
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var date = new Date(str);
if (date != "Invalid Date" && !isNaN(new Date(date) && !str.match(/a-z/g) )
alert(date);
}

"Is not a function" error message at string modification with JavaScript?

I'm trying to modify the value of a string given a condition in a ternary operator statement:
($.trim($("#la").val())) ? a = $("#la").val() : a = 'NaN'
However I'm getting the error message:
"NaN" is not a function
What have I got wrong?
You'd generally do that like this
var a = $.trim($("#la").val()).length ? $("#la").val() : NaN;
or in this case, where an empty string would be falsy, you could do
var a = $('#a').val() || NaN;
The issue with NaN not being a function is probably because you quoted it, so it's a string, but unquoting it wont make it a function, it's still a native property!
var a = ($.trim($('#la').val()).length > 0) ? $('#la').val() : 'NaN';
should give you what you want.
Try this one:
var value = $("#la").val();
var a = ($.trim(value).length>0) ? value : 'NaN';

Categories

Resources