Check if date is valid in js - javascript

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()}

Related

date.toLocaleDateString is not a function

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;
}

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())

JS If Condition of Undefined

I have a user database like this:
const user = {
subscription: {
plan: 'free_trial',
},
};
I need to check some condition before user changes plan.
const currentDate = new Date();
if (user.subscription.trialExpDate > currentDate) {
// do something
} else {
// trialExpDate is either undefined or <= currentDate
user.subscription.trialExpDate = currentDate;
}
My question is, for some users trialExpDate will be undefined. Is it okay to compare undefined against currentDate object? Or do I need to check if trialExpDate exist first?
I would suggest check with hasownproperty.
Sample:
if (user.subscription.hasOwnProperty('trialExpDate') && user.subscription.trialExpDate > currentDate) {
// do something
} else {
// trialExpDate is either undefined or <= currentDate
user.subscription.trialExpDate = currentDate;
}
You can just check if it is null.
if (user.subscription.trialExpDate != null || user.subscription.trialExpDate > currentDate) {
// do something
}
else {
// do something else
}
The variable != null will simultaneously check if the variable is null or undefined.
In short: if you're sure that user.subscription.trialExpDate cannot be a null, using your original code is very okay.
See how the JavaScript relational comparison operators coerce types.
If user.subscription always exist and it is always an object, comparison between a Date object, and an undefined or a NaN, is evaluated as false. However, for a null, it is evaluated as +0, thus null < (new Date) will be true, null > (new Date) will be false.
When JavaScript relational comparison works,
A Date object is converted to its timestamp, which is (The Date object).valueOf().
A primitive is converted to a number, which means:
an undefined is converted to a NaN;
a null is converted to +0.
Then the comparison is performed between each item as you'd expect for the operator. Note that any comparison involving a NaN evaluates to false.

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);
}

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.
For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)
What is the closest javascript (or jquery if then have one) call that would be equal?
You're overthinking. Null and empty string are both falsey values in JavaScript.
if(!theString) {
alert("the string is null or empty");
}
Falsey:
false
null
undefined
The empty string ''
The number 0
The number NaN
If, for whatever reason, you wanted to test only null and empty, you could do:
function isNullOrEmpty( s )
{
return ( s == null || s === "" );
}
Note: This will also catch undefined as #Raynos mentioned in the comments.
if (!string) {
// is emtpy
}
What is the best way to test for an empty string with jquery-out-of-the-box?
If you know that string is not numeric, this will work:
if (!string) {
.
.
.
You can create one Utility method which can be reused in many places such as:
function isNullOrEmpty(str){
var returnValue = false;
if ( !str
|| str == null
|| str === 'null'
|| str === ''
|| str === '{}'
|| str === 'undefined'
|| str.length === 0 ) {
returnValue = true;
}
return returnValue;
}
you can just do
if(!string)
{
//...
}
This will check string for undefined, null, and empty string.
To be clear, if(!theString){//...} where theString is an undeclared variable will throw an undefined error, not find it true. On the other hand if you have: if(!window.theString){//...} or var theString; if(!theString){//...} it will work as expected. In the case where a variable may not be declared (as opposed to being a property or simply not set), you need to use: if(typeof theString === 'undefined'){//...}
My preference is to create a prototype function that wraps it up for you.
Since the answer that is marked as correct contains a small error, here is my best try at coming up with a solution. I have two options, one that takes a string, the other takes a string or a number, since I assume many people are mixing strings and numbers in javascript.
Steps:
-If the object is null it is a null or empty string.
-If the type is not string (or number) it's string value is null or empty. NOTE: we might throw an exception here as well, depending on preferences.
-If the trimmed string value has a length that is small than 1 it is null or empty.
var stringIsNullOrEmpty = function(theString)
{
return theString == null || typeof theString != "string" || theString.trim().length < 1;
}
var stringableIsNullOrEmpty = function(theString)
{
if(theString == null) return true;
var type = typeof theString;
if(type != "string" && type != "number") return true;
return theString.toString().trim().length < 1;
}
you can say it by logic
Let say you have a variable name a strVal, to check if is null or empty
if (typeof (strVal) == 'string' && strVal.length > 0)
{
// is has a value and it is not null :)
}
else
{
//it is null or empty :(
}

Categories

Resources