This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: formatting number with exactly two decimals
Can some one please help me with my java script?
My java script consistently counts up, the problem is the cents character length is way too long (need 2 characters max). Another problem is, I don't know what code additionally I need to put commas in the correct position for determining the proper amount. Example: 12345.67 vs 12,345.67. If some one can just take a look at the code, modify it and re-post the full code since I have no idea what to do, I would deeply appreciate it.
This is the javascript code: http://jsfiddle.net/pqsH6/
<p style="float:left;">Money Saved: </p><b><p id="ds" style="float:left;">$</p></b>
<div id="counter" style="float:left;"></div>
<script type="text/javascript">
var START_DATE = new Date("january 1, 2012 12:00:00"); // put in the starting date here
var INTERVAL = 1000; // savings per second
var INCREMENT = 0.005; // money saved per second
var START_VALUE = -50000; // configures proper savings calculation
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = count;", msInterval);
}
</script>
This looks like a way to format your output with commas using Javascript:
How to print a number with commas as thousands separators in JavaScript
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Just pass your numbers through the function as a parameter and it will return a comma delimited number.
Here's another function you can use to round out to two decimal places:
function formatCurrency(num) {
num = isNaN(num) || num === '' || num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
Then use the function like this
var roundedCurrencyAmt = numberWithCommas(formatCurrency(amtOfMoney));
Here's a working jsFiddle: http://jsfiddle.net/alexfromapex/Y2x8m/2/
Just a comment:
> var START_DATE = new Date("january 1, 2012 12:00:00");
Relies on the built–in Date function parsing the string correctly, but ECMA-262 specifies only one format (a version of ISO8601) that Date should parse and that isn't it. But not all browsers in use support that format.
Better to use something that is both specified and known to work everywhere, e.g.:
var START_DATE = new Date(2012,0,1,12);
which will create a new date of 2012-01-01 12:00:00 in the local timezone in all browsers, or if UTC is required then:
var START_DATE = new Date(Date.UTC(2012,0,1,12));
Related
I'm having a form which is having two input fields with date picker(with the help of jquery ui).One asking a check in date & the other asking check out date.I want to calculate the Number of Days Between those two dates.I am a beginner to javascript.So can any one help me?
Use unix timestamp. It's universal tool when you working with time:
var a = new Date(2012,11,10);
var b = new Date(2012,11,12);
var dt = (b.getTime() - a.getTime())/(24*3600*1000) //2
You must first get the value of such input fields, eg:
var v1 = document.getElementById('input1Id').value;
var v2 = document.getElementById('input2Id').value;
then you have to instantiate two new Javascript Date objects:
var parts1 = v1.split('/');
var parts2 = v2.split('/');
// this will split your string into date parts, eg. 11/30/2012 would result as an array ['11','30','2012'];
var date1 = new Date(parts1[2],parts1[0],parts1[1]);
var date2 = new Date(parts2[2],parts2[0],parts2[1]);
// remember to check the index of array items considering your date format
finally, you just have to subtract one date from the other to get the difference in days:
var difference = Math.Abs(date1 - date2);
difference = parseInt(difference / 86400000);
//86400000 are the milliseconds in one day. Parsing to int will round the day - eg.5,4 days results as 5 day
Edit: Sure, you can reference your html element by his id attribute
<input type="text" id="myTextbox">
---
var txb = document.getElementById('myTextbox');
// do anything else to your txb here, if u like
txb.value = difference;
that's it!
I want to make this 1332251639632 to this 1332251639
I try this code, but since is not a string it dosent work
var date = new Date();
var t = date.getTime();
var p = t.substring(10);
alert(p);
I want to cut it since in php time() return 10 digit number
I have the opinion that a better approach is:
var dateObject = new Date(),
time = dateObject.getTime();
Math.floor ( time / 1000 );
Now the reasons are:
parseInt()ECMA Specs expects a string to be converted by a certain radix. Behind the scene the interpreter is working with strings and at the end returns integer number. Example MDN how the function is intended to work. As Chris Wesseling points the it is slower because of the additional work with the string and radix. ES5 which will be implemented in the future versions of the browsers, will impose the usage of radix, here is why:
parseInt( "011" ); //returns 9, 0 starting string is indicating octal number
parseInt( "011", 10 ); //returns 11, as expected
getTime()MDN will return a number, milliseconds since 1 January 1970 00:00:00 UTC, there is no convertion from string to number. This means "semantically" is better to use rounding function.
floor(x)ECMA Specs is intended to work with numbers. Returns the greatest Number value that is not greater than x. Usage MDN
ceil(x)ECMA Specs is almost the same - returns the smallest Number value that is not less than x. Usage MDN
A little off-topic Even the Linux y2k(38) problem won't make any difference because the number is 64-bit, and the integer in Javascript is presented in 53-bitsECMA Specs SO question.
Like this?
var p = parseInt(t/1000);
You could do it with rounding as suggested Ilia's solution, or with substring like this:
var date = new Date();
var t = date.getTime().toString();
var p = t.substring(0, 10);
alert(p);
How about this?
var date = new Date();
var t = date.getTime();
var p = parseInt(t.toString().match(/\d{10}/));
alert(p);
It converts the number into a string, matches the first 10 digits, then reconverts the result into number.
Try:
var t = "" + date.getTime();
var p = t.substring(0,10);
Curious whether there was any difference between
var p = parseInt(t/1000);
and
var p = Math.floor(t/1000);
I did this:
start = new Date().getTime(); for ( var i=0; i<1000000; i++) parseInt(start/1000); new Date().getTime() - start;
And
start = new Date().getTime(); for ( var i=0; i<1000000; i++) Math.floor(start/1000); new Date().getTime() - start;
In Chromium parseInt would take about 7.2 seconds against Math.floor 6.6 on my netbook.
Firefox complained about the script taking to long. It could only do 200000 operations in about the same time.
So I guess this is very implementation dependent.
I use a proprietary date format that looks like this:
var TheUserDate = "3.11.2012.4.3"; // is March 11th 2012 4:03AM
I created this format because my application uses a lot of timezone changes and I didn't want to rely on the browser's clock for that.
I have code like this everywhere:
var DateArray = TheUserDate.split(".");
var TheMonth = parseInt($.trim(DateArray[0]), 10);
var TheDay = parseInt($.trim(DateArray[1]), 10);
var TheYear = parseInt($.trim(DateArray[2]), 10);
How can I rewrite this so that it emulated the .getMonth() .getYear() functions that are built into javascript. I'm thinking I need to modify the prototype of strings but this is my first attempt at doing something like this. I'd like to have functions like:
var TheMonth = TheUserDate.getMyMonth();
var TheDay = TheUserDate.getMyDay();
var TheYear = TheUserDate.getMyYear();
var TheDate = TheUserDate.getMyDate(); // to convert my format back to a javascript date.
How should I do this?
Thanks.
Use the ISO8601 date format YYYY-MM-DD THH:mm:ssZ and there are datetime standardisation libraries for javascript, along with the UTC methods to avoid timezone issues. The biggest issue with Date values in JavaScript is that there is a lot of undefined behaviour in the Date objects. For anyone who needs a consistent Date api I would suggest using a fixed implementation that overrides the default Date object, allowing for consistent behaviour across all browsers, but do be careful if you have other libraries which are dependent on this.
I have used https://github.com/csnover/js-iso8601/ in the past without issues
http://www.w3.org/TR/NOTE-datetime
Does Javascript/EcmaScript3 support ISO8601 date parsing?
Update
As requested, to actually achieve what you want if you don't want to use a standards compliant date format, this is how you might go about implementing the object you want
var UserDate = (function () {
function UserDate(dateString) {
var dateArray= dateString.split('.'), i;
if (dateArray.length !== 5) {
// Handle this however you want, throw exception,
// bad date type etc
}
// No need to trim, parseInt doesn't care about
// leading or trailing whitespace
for (i = 0; i < dateArray.length; i += 1) {
dateArray[i] = parseInt(dateArray[i], 10);
}
// Check that the date array is well formed here if you want,
// check for NaN and value range
// ...
this._dateArray = dateArray;
}
// Creates a date string from the internal date array
UserDate.prototype.getDate = function () {
var dateString = "", i;
for (i = 0; i < this._dateArray.length; i += 1) {
dateString += this._dateArray[i];
if (i < this._dateArray.length - 1) {
dateString += ".";
}
}
return dateString;
};
// Returns the day value from the internal date array
UserDate.prototype.getDay = function () {
return this._dateArray[0];
};
// Returns the month from the internal date array
UserDate.prototype.getMonth = function () {
return this._dateArray[1];
};
// Returns the year from the internal data array
UserDate.prototype.getYear = function() {
return this._dateArray[2];
};
// Returns the hour from the internal date array
UserDate.prototype.getHour = function() {
return this._dateArray[3];
};
// Returns the minute from the internal date array
UserDate.prototype.getMinute = function() {
return this._dateArray[4];
};
// more prototypes here
return UserDate;
}());
With my tests in the console:
> var someDate = new UserDate("3.11.2012.4.3");
> someDate.getDate()
"3.11.2012.4.3"
> someDate.getYear()
2012
> someDate.getMonth()
11
> someDate.getDay()
3
> someDate.getHour()
4
> someDate.getMinut()
3
Seriously don't consider editing String.prototype to give you this functionality. It's very bad practice to extend the native prototypes in JavaScript unless you are really sure what you are doing. It certainly doesn't make any sense to be adding such bespoke functionality to a general purpose string object. If you need global access to this UserDate object then make it a global object as it would be in this example. The danger is that you don't know what third party libraries are doing to the prototype.
http://perfectionkills.com/extending-built-in-native-objects-evil-or-not/
Might be worth a read if you're interested in the arguments in general. If you really really really want to extend the string prototype then you could do something like
String.prototype.getDay = function () {
return this.split('.')[0];
}
But this will make me a sad chicken.
Dates are really simple.
var d = Date.now()
var dateString = new Date(d).toGMTString()
Store dates as the UTC timestamp and call new Date(timestamp).toGMTString() if you ever want to visually render it.
Is there any way in JavaScript that I can check if date is between 2 dates?
I have an array like
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
and now I have 2 dates like 1-7-2011 and 10-7-2011. I want to see if any value from unavailableDates falls between these date. If it falls it should return alert.
Can someone help me on this? I am in process of learning more about JavaScript and jQuery. I am not able to code it the way I understood the problem.
Here you have the solution
var unavailableDates = ["5-7-2011","6-7-2011","7-7-2011","15-7-2011","16-7-2011","17-7-2011" ];
function str2date(sdate){ //This function gets a string and return a Date object
var parts = sdate.split("-");
return new Date(parts[2], parseInt(parts[1], 10)-1, parts[0]);
}
var stamp1 = str2date("1-7-2011").getTime(); //First date. getTime() converts it to an integer
var stamp2 = str2date("10-7-2011").getTime(); //Second date
for(var i=0; i<unavailableDates.length; i++){
var curStamp = str2date(unavailableDates[i]).getTime();
if(curStamp >= stamp1 && curStamp <= stamp2) //Check if it falls in range
alert(unavailableDates[i] + " falls in range");
}
Hope this helps. Cheers
Date object in JavaScript allows compare operation, you only required to have proper Date objects. Create Date objects from your bounds and array members and compare them in a loop.
More information about Date object could be found there: http://www.w3schools.com/js/js_obj_date.asp
I noticed Date.Parse can't handle only 2 digits dates.
Say I have this
mm/dd/yy = 7/11/20
Date parse will think it is = 7/11/1920. Can you set it to use the year two thousand? Like it's kinda weird I got the jquery u.i date picker and if you type in 7/11/20 it will figure out 2020.
So it would be nice if Date.parse could keep up I rather have them both not know what is going on or both know what is going on then have one that knows and one that does not know.
Not that I'm aware of. But you can always adjust the year:
YourDate="7/11/20";
DateObj=new Date(YourDate.replace(/(\d\d)$/,"20$1"));
alert(DateObj);
This code in action.
Edit: The following code will handle both full and short years:
YourDate="7/11/2020";
DateObj=new Date(YourDate.replace(/\/(\d\d)$/,"/20$1"));
alert(DateObj);
This code in action.
So your question is whether you can change the way Date.parse works so that low-numbered two-digit dates are interpreted as dates after the year 2000?
Yes, it can be done, simply shadow Date.parse with your own parse function.
// don't do this!
Date.parse = function (str) { /* your parse routine here */ }
Of course, it's generally a very bad idea to shadow properties (including 'methods' aka function properties) of host objects, because it will cause incorrect behavior in other scripts that expect those properties to work a certain way.
It's also a bad idea to use two digit dates, but that might be beyond your control. If it's not beyond your control, I'd advise to just forget 2-digit dates and use the full year value instead.
Here is my solution:
function parseDate(stringValue)
{
var date = new Date(stringValue);
if (!isNaN(date.getTime()))
{
// if they typed the year in full then the parsed date will have the correct year,
// if they only typed 2 digits, add 100 years to it so that it gets translated to this century
if (stringValue.indexOf(date.getFullYear()) == -1)
{
date.setFullYear(date.getFullYear() + 100);
}
return date;
}
else
{
return null;
}
}
How about this?
var date = '7/11/20';
var idx = date.lastIndexOf('/') + 1;
date = date.substr(0,idx) + '20' + date.substr(idx);
var result = Date.parse(date);
alert(result);
or this version that will test for a YYYY format first.
var date = '7/11/2020';
var idx = date.lastIndexOf('/') + 1;
if(date.substr(idx).length < 4) {
date = date.substr(0,idx) + '20' + date.substr(idx);
}
var result = Date.parse(date);
alert(new Date(result));