I want to do something like
var date = new Date();
var pretime = date.getTime();
$.post(
"ajaxfile.php",
object,
function(data) {
var totalTime = date.getTime()-pretime;
$("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
});
});
That is, measure how long the AJAXcall lasts before I get a response. But the print from this callback function is:
Time: 0
1326184886814
1326184886814
What is the solution to this?
getTime() is returning the same value because you are reusing the same Date() object. You need to create a new Date object:
var date = new Date();
var pretime = date.getTime();
$.post("ajaxfile.php", object, function(data){
var date2 = new Date();
var totalTime = date2.getTime()-pretime;
$("#feed").append("Time: " + totalTime + "<br/>" + pretime + "<br/>" + date.getTime() + "<br/>");
});
});
I'm no Javascript expert, but it seems to me that you're creating a single Date object which (if it's similar to Java's Date object) stores the date/time at the point it was created, and then using that same date object twice - i.e. comparing the start date/time to itself.
Try creating a second Date object inside the AJAX callback function to capture the end time.
If you are just interested in the time, without saving it somewhere, you can use Google Chrome's developer console.
press F12, go to "Network" tab, execute your Ajax call, and you can see a timeline of how long it takes you to get a response.
If you use firebug to debug your Javascript code take a look at the console. It will tell you how many miliseconds your ajax call takes :)
Also, if you don't use firebug, what are you waiting for? It is awesome for debugging and will save you lots of time!
Related
I'm writing a stored procedure for Cosmos DB. I am not very familiar with JavaScript.
I've been trying to get an ISO-8601 formatted Date, but have been unsuccessful so far. According to some docs I found, I should just be able to call toISOString on a Date. That does not work ("Object doesn't support property or method" error).
So I found this advice to define the prototype yourself:
function storedProcedure(arg) {
if (!Date.prototype.toISOString) {
// Here we rely on JSON serialization for dates because it matches
// the ISO standard. However, we check if JSON serializer is present
// on a page and define our own .toJSON method only if necessary
if (!Date.prototype.toJSON) {
var toISOString = function (date) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return date.getUTCFullYear() + '-' +
f(date.getUTCMonth() + 1) + '-' +
f(date.getUTCDate()) + 'T' +
f(date.getUTCHours()) + ':' +
f(date.getUTCMinutes()) + ':' +
f(date.getUTCSeconds()) + 'Z';
};
}
Date.prototype.toISOString = Date.prototype.toJSON;
}
var now = Date.now();
var iso8601 = now.toISOString();
console.log("ISO " + iso8601);
// other code
}
However, this still fails with:
Object doesn't support property or method 'toISOString'
I tried removing the prototype altogether and just using a function that takes a Date instead. However, then the same error occurred but for other members, like getUTCFullYear.
I tried also calling getSeconds and that failed for the same reason. Out of desperation, I tried listing out the object's properties using the getKeys function in this answer and it gives me an empty list.
What is going on here? How can I just get an ISO-8601 formatted Date representing the current time in UTC?
OK, it seems it was because I had used Date.now() per these docs instead of new Date() per this random google result.
I have no idea why this matters or how I could have known this (explanations welcome) but that was the underlying cause. I don't even need the prototype now.
I want to get time from server for the first time and then update it by JavaScript every second. This is my code:
setInterval(function() {
var myvar = '<?php echo strtotime($now); ?>'
var hours = myvar.getHours();
var minutes = "0" + myvar.getMinutes();
var seconds = "0" + myvar.getSeconds();
myvar=hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("time").innerHTML=myvar;
}, 1000);
But it has error in the second line. The error is "myvar is not a constructor". So how can I do it?
1st problem is that your PHP is echoing an integer and setting myvar to that integer. The integer doesn't have a getMinutes, getHours... function. Instead, use aDate object.
2nd problem is that your function doesn't really advance the time because every iteration, myvar is reset to the initial value (the PHP echo is only run once, before the browser downloads the page). What you need is myvar to hold the correct time every time.
3rd problem is that you're using setTimeout which only runs once. Instead you should be using setInterval which will run every second.
The solution is to set a start time outside the function, then increment it and use it each round:
//PHP will set the start time
var start = <?=time()?>;
setInterval(function(){
//add 1 second and set myvar to the correct current time
start++;
var myvar = new Date(start * 1000);
...
},1000);
You may have to make a small adjustment, because some time will elapse between when PHP writes the start value and when the JavaScript is loaded and run in the browser. This will make the JS time lag a bit behind server time.
Live demo
You can use .getHours(), .getMinutes() function only with javascript date not with php date. One way you can use is :
setInterval(function() {
var myvar = new Date();
var hours = myvar.getHours();
var minutes = "0" + myvar.getMinutes();
var seconds = "0" + myvar.getSeconds();
myvar=hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
document.getElementById("time").innerHTML=myvar;
}, 1000);
if you use php you can't update the time
strtotime returns a integer that represents the current time.
You're storing that in a variable, as an string.
Your compiled php file will look something like this:
setInterval(function() {
var myvar = '1468845612'
myvar is just a ordinary string, there. That string doesn't have an .getHours function.
replace that var myvar line with this:
var myvar = new Date(<?php echo strtotime($now); ?>000);
Rendered output:
var myvar = new Date(1468845612000);
Notice how I added the 000 in there.
strtotime returns a timestamp in seconds. JavaScript's Date constructor expects a timestamp in milliseconds.
That all said, the setInterval call is pointless.
The php snippet will run only once, on page load. Then the interval will show the same date every second it's executed.
I would like to convert a Javascript date format to ASP.NET date format.
2012-09-10 12:00PM to /Date(1347442050050-0700)/
Because I'm passing it back to the server. I got the ASP.NET format from the request I did on the server, then convert it to Javascript date using moment.js:
moment("/Date(1347442050050-0700)/").format("YYYY-MM-DD hh:mmA");
Is there a way to do this?
I got what i need. If this is somehow wrong please comment.
var test = moment("2012-09-10 12:00PM").valueOf();
var test2 = moment("2012-09-10 12:00PM").format("ZZ");
var test1 = "/Date("+test+test2+")/";
alert( test1 ); // returns /Date(1347206400000+0800)/
var string = moment(test1).format("YYYY-MM-DD hh:mmA");
alert( string ); // returns 2012-09-10 12:00PM
You can add the function to the moment prototype so that it's a little more portable.
http://jsfiddle.net/timrwood/qe8pk/
moment.fn.toASP = function () {
return '/Date(' + (+this) + this.format('ZZ') + ')';
}
If you want to send a date back to an ASP.NET ASMX web service where the RPC method receives a DateTime object, this may be helpful: https://stackoverflow.com/a/12973157/1145963
I have to display datetime value on my real time page and i have done following jquery function for that.
function DisplayTimer() {
var x = new Date();
$('#<%=lblTimer.ClientID %>').html(x.toString());
setTimeout('DisplayTimer()', 5000);
}
now i have timezonid value in my session object how can i convert above date value to custom timezone using timezonid session value and also want set datetime format as per culture of user's browser through this jquery function. I have solution in server side code so using [webmethod] i can do that it will make separate request for that every 5 second so i would like to do that without server side interaction. please help me if anyone done this type of logic.
Thanks in adavance.
Change your code with:
var ClientDatetime = x.getMonth() + "/" + x.getDate() + "/" + x.getYear() + " "
+ x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();
take one hidden variable hdnClientDateTime with runate = server and set value as following
hdnClientDateTime.value = ClientDatetime;
Now, Pass hdnClientDateTime.value variable in your server side Datetime format function and assign the value into label like this:
$('#<%=lblTimer.ClientID %>').html(Result);
I have a MVC application that produces the following output in a browser when I visit a certain URL:
[{"name":"Victoria Day","date":"\/Date(1337583600000)\/"},{"name":"Canada Day","date":"\/Date(1341212400000)\/"},{"name":"Civic Holiday","date":"\/Date(1344236400000)\/"},{"name":"Labour Day","date":"\/Date(1346655600000)\/"},{"name":"Thanksgiving","date":"\/Date(1349679600000)\/"},{"name":"Remembrence Day","date":"\/Date(1352707200000)\/"},{"name":"Christmas","date":"\/Date(1356422400000)\/"},{"name":"Boxing Day","date":"\/Date(1356508800000)\/"}]
Of course, the source code has a bunch of html tags wrapped around that.
How can I assign this raw information to a Javascript array?
Considering your http request returns the raw data that you've posted, you should be able to use:
var text = $.trim($(document.body).text());
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!
alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());
// Output(the dates should be printed with your preferred timezone offset):
// Loaded 8 holidays. Fifth one is Thanksgiving celebrated on Mon Oct 08 2012 10:00:00
// GMT+0300 (GTB Daylight Time)
If that output that you want to parse resides in other place, you should load it via jQuery in var text using your custom selector. Note that var cleanedText removes the bad characters from date values, in order to parse them as valid javascript Date objects.
Leave a comment if you have further questions. Good Luck!
JSFiddle working example: click here
Edit: You need jQuery.
Edit2: I think you need to use $.get in order to retrieve your data from a custom url(make sure it's from the same server or you might run into browser security issues). You should play a little with this and try check if your request goes to the correct path on the server(for example you can check on Google Chome browser under Developer Tools on Network tab all requests data). You should change the content of function(data) { to match your needs.
var url = 'page.html'; // You should change this with the url that returns your data.
$.get(url, function(data) {
alert('The response is: ' + data); // Make sure it's ok
var text = $.trim(data);
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!
alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());
});
Get jQuery and use jQuery.getJSON, for example...
That is called JSON. You can use an external library like json2.js to parse it, or if you don't care about old browsers, use the native version,
var myData = JSON.parse('..data');