<script>
dfrom = datefrom.split("/");
dto = dateto.split("/");
//Checking Year Part;
if(parseInt(dfrom[2]) > parseInt(dto[2])){
alert("DateFrom Cannot greater than DateTo");
return false;
}
if((parseInt(dfrom[1]) > parseInt(dto[1])) && parseInt(dfrom[2]) == parseInt(dto[2])){
alert("DateFrom Cannot greater than DateTo");
return false;
}
if(parseInt(dfrom[0]) > parseInt(dto[0]) && (parseInt(dfrom[1]) == parseInt(dto[1])) && parseInt(dfrom[2]) == parseInt(dto[2])){
alert("DateFrom Cannot greater than DateTo");
return false;
}
</script>
This is my script code to compare dates and is working fine but when I check 07/04/2013 and 08/04/2013, it shows "DateFrom Cannot greater than DateTo" and only these dates are showing wrong result. Is any error in my script or something else?
Any help would be highly appreciable.
try this
dfrom = datefrom.split("/");
dto = dateto.split("/");
var x=new Date();
x.setFullYear(dfrom [2],dfrom [1]-1,dfrom [0]);
var y=new Date();
y.setFullYear(dto [2],dto [1]-1,dto [0]);
if (x>y)
{
alert("X is big ");
}
else
{
alert("Y is big");
}
see here
When interpreting the parseInt function's arguments, older browsers will use the octal radix (base-8 numbering system) as default when the string begins with "0" (e.g., '07', '08'). As of ECMAScript 5, the default is the decimal radix (10) (i.e., this is tricky, but at least now it is depreciated).
In other words, there is a chance that if you pass strings ("01") or numbers (01) that begin with 0 to parseInt without specifying the second parameter (radix, which means what numbering system), they will be interpreted as having radix 8. This means 07 === 7 and 08 probably has undefined behavior (0, "", undefined, who knows?).
To be safe, always set your radix in the second parameter to parseInt when dealing with dates (I know I do), for example parseInt(x, 10) for regular base 10.
By the way, leading numbers with 0 indicates the octal radix other languages, so it is a good to get rid of them when converting strings to numbers.
Good luck!
The easiest way to compare date strings is to turn them into date objects and compare those, so if your date strings are in the format d/m/y. you can do:
// s in format d/m/y
// e.g. 15/3/2013 or 15/03/2013
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
var d0 = '3/3/2013';
var d1 = '15/3/2013';
// Compare dates
alert( toDate(d0) < toDate(d1) ); // true
alert( toDate(d1) < toDate(d0) ); // false
When used in a comparison or arithmetic operation, Date objects are coerced to a number that is their time value.
Related
I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);
I want to convert a number start with 0 to string equivalent of the value.
If I run
var num = 12;
var int = num.toString();
console.log(int);
it logs 12 as expected but if I apply the toString() to a number start with 0 like,
var num = 012;
var int = num.toString();
console.log(int);
it logs 10, why?
Number starting with 0 is interpreted as octal (base-8).
In sloppy mode (the default) numbers starting with 0 are interpreted as being written in octal (base 8) instead of decimal (base 10). If has been like that from the first released version of Javascript, and has this syntax in common with other programming languages. It is confusing, and have lead to many hard to detect buggs.
You can enable strict mode by adding "use strict" as the first non-comment in your script or function. It removes some of the quirks. It is still possible to write octal numbers in strict mode, but you have to use the same scheme as with hexadecimal and binary: 0o20 is the octal representation of 16 decimal.
The same problem can be found with the function paseInt, that takes up to two parameters, where the second is the radix. If not specified, numbers starting with 0 will be treated as octal up to ECMAScript 5, where it was changed to decimal. So if you use parseInt, specify the radix to be sure that you get what you expected.
"use strict";
// Diffrent ways to write the same number:
const values = [
0b10000, // binary
0o20, // octal
16, // decimal,
0x10 // hexadecimal
];
console.log("As binary:", values.map( value => value.toString(2)).join());
console.log("As decimal:", values.join());
console.log("As ocal", values.map( value => value.toString(8)).join());
console.log("As hexadecimal:", values.map( value => value.toString(16)).join());
console.log("As base36:", values.map( value => value.toString(36)).join());
All you have to do is add String to the front of the number that is
var num = 12;
var int = String(num);
console.log(int);
And if you want it to look like this 0012 all you have to do is
var num = 12;
var int = String(num).padStart(4, '0');
console.log(int);
So I have this script:
function makeActive() {
var element, name, arr;
element = document.getElementById("liveChat");
name = "active";
arr = element.className.split(" ");
if (arr.indexOf(name) == -1) {
element.className += " " + name;
}
}
var currentTime = new Date();
var currentTimeFormatted = currentTime.toLocaleTimeString();
if(currentTimeFormatted >= '08:00:00' && currentTimeFormatted <= '16:30:00'){
makeActive();
}
Which works perfectly in Chrome, however in IE the class doesn't get added.
If I remove the
&& currentTimeFormatted <= '16:30:00'
IE also adds the class. Why would adding a second condition, break this script within IE?
To make this a tad easier than having to use && and || mix, or if your values are stored somewhere in a static file etc. You could create a kind of pseudo time, by multiply each section.
eg.
const cTime = new Date();
const ptime =
cTime.getHours() * 10000 +
cTime.getMinutes() * 100 +
cTime.getSeconds();
if (ptime >= 80000 && ptime <= 163000) {
console.log("Active");
} else {
console.log("InActive");
}
You are doing string comparisons, which means that the browser and locale dependent output of toLocaleTimeString() screws your code in IE, and possibly also in other browsers or regions, because this function is solely intended for producing a human-readable time representation.
So you should either:
(1) Use a string representation that is standardized, e.g. invoking toISOString(). This will also get rid of time zone problems, because the result will always be in UTC time:
var currentTimeFormatted = new Date().toISOString(); // 2018-11-07T12:28:12.448Z'
currentTimeFormatted = currentTimeFormatted.substr(currentTimeFormatted.indexOf('T') + 1, 8); // 12:27:12
Now the rest of your code will work (assuming you 08:00:00 and 16:30:00 are UTC times).
(2) Extract the hour and minute parts of the new Date() and compare those to integers:
var currentTime = new Date();
if(currentTime.getHours() >= 8
&& // similarly a comparison to < 16:30
) {
makeActive();
}
(3) Use the great solution by Keith (see below), which I think is the best way to go
IE's implementation of date.toLocaleTimeString() adds non-printable characters into the string. The easiest way to deal with them is to trim them from the string;
currentTimeFormatted = currentTime.toLocaleTimeString().replace(/[^ -~]/g,'')
When dealing with localized timezones and timezone comparison, it might be worth trying a library like moment.js which can also deal with comparing values using the isBetween funciton
Edit
As the other solutions have suggested - using toLocaleTimeString() is not a safe method of performing date comparison and should be avoided.
It works with a lot number types, but not with negatives hexadecimal or binary.
Too, Number(octal) doesn't parse an octal number.
Number("15") === 15; // OK
Number("-15") === -15; // OK
Number("0x10") === 16; // OK
Number("0b10") === 2; // OK
Number("-0x10") === NaN; // FAIL (expect -16)
Number("-0b10") === NaN; // FAIL (expect -2)
Number("0777") === 777; // FAIL (expect 511)
Number("-0777") === -777; // FAIL (expect -511)
Question: how I can parse all valid Javascript numbers correctly?
Edit A
parseInt() don't help me because I need check by each possibility (if start with 0x I use 16, for instance).
Edit B
If I write on Chrome console 0777 it turns to 511, and too allow negative values. Even works if I write directly into javascript code. So I expect basically a parser that works like javascript parser. But I think that the negative hexadecimal, for instance, on really is 0 - Number(hex) in the parser, and not literraly Number(-hex). But octal values make not sense.
Try this:
parseInt(string, base):
parseInt("-0777", 8)
parseInt("-0x10", 16)
You could write a function to handle the negative value.
function parseNumber (num) {
var neg = num.search('-') > -1;
var num = Number(num.replace('-', ''));
return num * (neg ? -1 : 1);
}
It's not parsing octal and the other examples because they're not valid Javascript numbers, at least within the constraints of Number. So the technically correct answer is: use Number!
If you want to parse other formats, then you can use parseInt, but you will have to provide the base.
This gets a little ugly, but you could inspect the values to determine the right radix for parseInt. In particular, the b for binary doesn't seem to be support by my browser (Chrome) at all, so unlike the OP, Number("0b10") gives me NaN. So you need to remove the b for it to work at all.
var numbers = [
"15", "-15", "0x10", "0b10", "-0x10", "-0b10", "0777", "-0777"
];
function parser(val) {
if (val.indexOf("x") > 0) {
// if we see an x we assume it's hex
return parseInt(val, 16);
} else if (val.indexOf("b") > 0) {
// if we see a b we assume it's binary
return parseInt(val.replace("b",""),2);
} else if (val[0] === "0") {
// if it has a leading 0, assume it's octal
return parseInt(val, 8);
}
// anything else, we assume is decimal
return parseInt(val, 10);
}
for (var i = 0; i < numbers.length; i++) {
console.log(parser(numbers[i]));
}
Note this obviously isn't foolproof (for example, I'm checking for x but not X), but you can make it more robust if you need to.
I have the following code in an external javascript file. I am getting an error on this line below: guessNum = inGuess.parseInt();
firebug tells me the parseInt is not a function. I thought all things in js were basically objects (at least that is what I remember reading in W3School). I am sure this is something simple, I am just stuck. Any suggestions are welcome. Thanks
function inputNum()
{
/* initialize variables */
var inGuess = "";
var loopCt;
var guessResult = "";
var correctNum = 26;
var guessNum = 0;
for (loopCt=1;loopCt<11;loopCt++)
{
inGuess = prompt("Please enter your guess(enter -1 to exit) Do not press Enter","0");
if (inGuess == "-1") { break; }
if (inGuess==null || inGuess=="")
{
alert("Blanks are not allowed. To exit enter '-1'.");
}
else
{
guessNum = inGuess.parseInt();
if (inGuess == "26")
{
alert("Congratulations, you guess correctly!");
guessResult="Correct!";
}
else
if (guessNum < correctNum)
{
guessResult="Too low";
}
else
{
guessResult="Too high";
}
document.getElementById('emp'+loopCt).innerHTML=inGuess;
document.getElementById('ct'+loopCt).innerHTML=guessResult;
}
}
}
parseInt is a global function. You are trying to access it off of a string object, where it doesn't exist.
guessNum = parseInt(inGuess, 10); // Tell it what base to use. Protect against 08 being interpretued as octal.
That would be the correct way to handle this.
parseInt Mozilla Developer Network Docs
Footnote - parseInt can return NaN which when compared with typeof actually returns number
parseInt is a method on window, not on a string. You want
guessNum = parseInt(inGuess, 10);
The second argument insures that your code will treat the first argument as a base-10 number, meaning it will correctly parse "010" as 10 and reject "0x10" instead of parsing it as 16.
I thought all things in js were basically objects
They are objects, but that doesn't mean that all objects have the same set of methods defined on them.
If you do want to use it like that for whatever exotic reason, you can define prototype on the String object:
String.prototype.parseInt = function() {
return parseInt(this,10);
}
var inGuess = "26";
alert(inGuess.parseInt());
Your syntax isn't quite right... From the console:
> x = parseInt("2", 10)
2
Also, something to keep in mind, which come from the docs...
If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
parseInt() Documentation
inGuess is a string and string does not have parseInt function. parseInt is a global function.
do this:
guessNum = parseInt(inGuess);