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())
Related
I have a TypeScript class without any import statement at the top. When I new calculateDate() and execute addMonth(new Date(), 1), it adds 11 months to today instead of 2. The m variable is always a result of string concatenation, instead of math addition operation. I even tried parseInt() with the string form of the two operands, it still performs string concatenation. Please help. Thanks.
export class calculateDate {
addMonth(thisDate:Date, monthCount:number){
if (thisDate && monthCount && monthCount != -1) {
let m : number = thisDate.getMonth() + monthCount;
console.log('m=', m);
let newDate: Date = new Date(thisDate.setMonth(m));
return newDate;
}
else
return null;
}
}
You are adding up two strings, try to parse them as int or use this syntax +thisDate.getMonth() + (+monthCount)
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;
}
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);
}
I need to find a string from the body and if result is true - redirect to another page.
I've tried something like this ..
var str = document.documentElement.innerHTML;
var re = 'someWord';
if (str.search(re) = -1)
{
location.replace("http://google.com");
}
but it doesn't work.
I am new to javascript, so i need your help. Thanks in advance !!
You should read your error message. Given that code, you should be seeing this error:
ReferenceError: Invalid left-hand side in assignment
So it looks like you are doing an invalid assignment, perhaps here?
if (str.search(re) = -1){
Yeah, you probably meant an equality check instead:
if (str.search(re) == -1){
Use indexOf function of javascript:
Case sensitive:
if (str.indexOf("someWord") >= 0)
Case insensitive:
if (str.toLowerCase().indexOf("someword") >= 0)
Please try this
var str = document.documentElement.innerHTML;
var re = 'someWord';
if (str.search(re) == -1){
location.replace("http://google.com");
}
I have some code for validating date below:
function validateForm() {
var errFound = 0;
//var patt_date = new RegExp("^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|(1[0-2]))-(29|30)))))$");
var patt_date = new RegExp("^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$");
if (patt_date.test(document.getElementById("datefrom").value) == false){errFound = errFound + 1;document.getElementById("datefrom").className = "error";}
if (errFound > 0)
alert('Please correct red colored field!');
else
return true;
return false;
}
Above code should work with YYYY-MM-DD format, but fail to validate date such as "2009-02-29"
The commented code should work (//var patt_date = new RegExp...), it can catch "2009-02-29", but it ruin the validation when i put invalid data and try to correct it, it keeps complain there something wrong with form value after i had correct them (especially on form with multiple input)
Maybe someone can fix the current regex?
Edited, what i want just a simple replacement for above regexp, mean a new regexp pattern not the whole new method to validate date
And for reference, i simply grab the regexp pattern from:
http://www.regexlib.com/REDetails.aspx?regexp_id=694 and
http://www.regexlib.com/REDetails.aspx?regexp_id=933
Tested with 2009-02-29, 1st link work & 2nd not. Again the problem was only the 2nd regexp didn't detect value 2009-02-29 as invalid while 1st can (but it ruin my code? so it's must be there something wrong with it).
Thanks,
Dels
Don't do the whole date validation with a regular expression, that's really pushing the limits of what regexps were designed for. I would suggest this procedure instead:
Check date against regexp /^\d{4}-\d{2}-\d{2}$/
Extract year, month, and day using substr() and convert to integers
Use some if statements to validate the integers. Like so:
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
// fail
}
}
else if (day > 28) {
// fail
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
// fail
}
}
else {
if (day > 31) {
// fail
}
(That could certainly be written more concisely) Alternatively, you could probably perform this validation using Javascript's Date class - you might have to do something like parsing the date, converting it back to a string, and checking if the two strings are equal. (I'm not a Javascript expert)
I kinda agree with David on this... Regex matches should not be used as an exclusive criterion to decide if the passed date is, in fact, valid. The usual procedure in Javascript validation involves a few steps :
a. The first step is to ensure that the passed string matches expected date formats by matching it against a Regex. The following may be a stricter Regex pattern.
// Assuming that the only allowed separator is a forward slash.
// Expected format: yyyy-mm-dd
/^[12][90][\d][\d]-[0-3]?[\d]-[01]?[\d]$/
b. The second step is to parse the string into a Date object which returns the no. of milliseconds since 1970. Use this number as a parameter for the Date constructor.
c. Since JS automatically rolls over the passed date to the nearest valid value, you still cannot be certain if the Date object created matches that which was passed. To determine if this happened, the best way is to split the passed string according to the separator and compare individual date components:
// d is the created Date object as explained above.
var arrDateParts = inputDate.split("-");
if ((d.getFullYear() == arrDateParts[0]) && (d.getMonth() == arrDateParts[1]) && (d.getDate() == arrDateParts[2]))
return true;
else
return false;
This javascript code validates date exactly. You can copy it and test it in your browser.
var regDate = '^(19[0-9]{2}|2[0-9]{3})-(0[1-9]{1}|1[0-2]{1}){1}-(0[1-9]|(1|2)[0-9]|3[0-1]){1}$';
var txt='2010-01-31';
if(txt.match(regDate))
{
alert('date match');
}