highcharts gets my hour time wrong
I'm from venezuela just in case. I doing a real time system where I get in my db the time,seconds and miliseconds like
10:39:09:2
I apply the strtotime($time) then I sended by json to charted
and in my highcharts i got in the
xAxis: {
type: 'datetime',
title: {
text: 'Tiempo'
}
the utc function is already false
Highcharts.setOptions({
global: {
useUTC: false
}
});
and my function to get the json is
function requestData_Frecuencia() {
$.ajax({
url: 'Datos_Frecuencia.php',
success: function (point) {
var series = chart_Frecuencia.series[0],
shift = series.data.length > 400;
//add point
chart_Frecuencia.series[0].addPoint(eval(point), true, shift);
setTimeout(requestData_Frecuencia, 500);
},
cache: false
});
}
PS. is been a while since I write in english so forgive me if I write something wrong o that isn't clear.
You should check the raw values in the database. I know that MySQL stores dates in GMT. Not sure about the DB you are using, but the reason that this is done is:
GMT is an absolute time reference & doesn't change with the seasons.
You will have to convert the time to your locale, which is UTC–04:30
Have a look at: Convert date to another timezone in JavaScript
Highcharts doesn't include timezones and only what you can do is disabling UTC,aas you have. THen you need to translate your data or use label formatter / tooltip formatter to display correct data.
I found out what I was doing wrong (found the answer here ). I used to get my time in php like:
while($r2 = pg_fetch_array($sth)) {
$hora = $r2['hora'];
$Frecuencia = $r2['frecuencia'];
}
$x=strtotime($hora);
I needed to multiplied by 1000 the time. I think, is because I need to suggested that date is in form of miliseconds (that is integer)
while($r2 = pg_fetch_array($sth)) {
$hora = $r2['hora'];
$Frecuencia = $r2['frecuencia'];
}
$x=strtotime($hora)*1000;
PD: thanks to everybody anyway for the suggestion and responses given. I really appreciated
Related
I have a javascript date that I am passing via ajax to a php script then using the date in an sql insert into mysql database. I can't figure out how to format the date so the SQL call accepts it. Can anyone help with this?
In the AJAX call I've tried passing the date object as is, converting to JSON, to UTC.
The error I get is:
Incorrect date value: 'Thu, 01 May 1902 03:01:00 GMT' for column 'uspr_dob'
This all works if I remove the date line from the SQL code. ie I update the other fields but not the date. So everything else is working except the date passing.
jQuery date formation:
var dob = new Date(year, month, day, hours, minutes, 0, 0);
jQuery AJAX call:
var save_result = jQuery.ajax({
url: lb_path + "update_user.php",
data: { 'lb_user_id' : this.id,
'lb_dob' : this.dob.toUTCString(), //toJSON
... },
type: 'POST',
datatype: 'json',
success: function(data, status) {
...
}, // End success
error: function (xhr, ajaxOptions, thrownError) {
...
}
}); // End load the supplement list
PHP code is:
$sql = "UPDATE userpref
SET uspr_person_group = \"".$lb_gender."\",
uspr_diet_type = (SELECT diet_id FROM diet WHERE diet_name = \"".$lb_diet."\"),
uspr_exercise_profile = (SELECT exprof_id FROM exercise_profile WHERE exprof_name = \"".$lb_exercise."\"),
uspr_dob = \"".$lb_dob."\"
WHERE uspr_user_id = ".$lb_user_id;
If you use YYYY-MM-dd format you will never run into any issues. It is better to convert it before passing it to the server in your case.
Please refer to Get String in YYYYMMDD format from JS date object? .
OK - I found the problem - The database documentation showed the field in the table was DATETIME ... when actually it was DATE.
Once I spotted that and massaged the datetime string into MySQL's format it all worked beautifully!
Still I would think that there is an easier way to do this ... ie a date format in javascript that can be passed straight through AJAX, PHP then SQL and work without any formatting.
I am bringing in data that looks like this via PHP:
Sun Jun 26 02:00:01 EDT 2016
It becomes this variable:
$arr_dates[] = date("m/d/Y H:i", strtotime($datestr, time()));
And becomes used in Highcharts:
series: [{
name: '# users online',
data: [<?php echo "\n"; foreach ( $arr_num_users as $i ) { echo "[Date.parse('".$arr_dates[$ct]."'),".$i."],\n";$ct++; } echo "\n]"; ?>
}
So when I (EDT timezone) view it, the graph shows up correctly and the times are displayed as GMT+0.
But anyone else using a different timezone, the times are off. So someone in PDT will see a graph that is skewed by 3 hours which is incorrect. It should always be a set time, or at least accurate.
How can I fix this? setUTC did not seem to help.
Highcharts.setOptions({
global: {
useUTC: true
}
});
$('#container').highcharts({
chart: {
zoomType: 'x'
},
rangeSelector : {
selected : 1
},
.....
I've also tried without any setOptions at all, nothing changes.
This is under Highcharts v3.0.10
To be clear, the time on the chart is changing based on the users' timezone. I do not want that to happen.
You can view the issue here: http://observit.org/rffxiv.php (switch to EDT for your timezone which displays correctly, then to something else and refresh; issue will be shown)
This worked for me.
Highcharts.setOptions({
global: {
timezoneOffset: 5 * 60 //EST offset
}
});
I have Kendo UI grid when I save a new date value, the value send as POST request like
Wed Jun 19 2013 17:48:32 GMT+0200 (Egypt Standard Time)
I am trying to take this value and send to the web service which waiting value with type "DateTime"
I want to convert the sending value date even in Kendo UI before send as POST value or
in the PHP file when I receive this value
Any Help ?
kendo ui allow set culture and date format adding
please checkout http://docs.kendoui.com/api/framework/kendo#culture
http://docs.kendoui.com/getting-started/framework/globalization/dateformatting
Reading i found this:
http://www.kendoui.com/forums/framework/globalization/kendo-fails-to-parse-or-format-utc-dates.aspx
parameterMap: function (options, operation) {
if (operation != "read") {
var d = new Date(options.Date);
options.Date = d.toString("yyyy-MM-dd");
return options;
}
}
{ field: "Date", title: "Date ", type: "date", format: "{0:dd/MM/yyyy}" }
result : 30/08/2012
kamal , I think this would be the solution and this how I solve it
parameterMap: function (options, operation) {
if (operation != "read") {
//change the fieldDate variable to your field date
var d = new Date(options.models[0].fieldDate);
options.models[0].fieldDate = kendo.toString(new Date(d), "yyyy-MM-dd");
return options;
}
}
it might help someone like me ...
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
For my Visualization Table, i populated data from server side using PHP as guided by http://code.google.com/apis/chart/interactive/docs/php_example.html. I have two columns with time. Now i given 'string' type to this column and pass 12 hour format time. The response Json draw table properly. But sorting not works properly in 12 hour format.It sorts only depends on first two characters. It does not consider the am , pm.
I want to sort the am,pm time properly.I have tried to pass 24 hour format data from server and receive it javascirpt and try to format the time. But It is also not works properly.Please help me resolve this problem.
function drawTable() {
var username="Raja";
var curdate="19/03/2012";
var jsonData = $.ajax({
url: "cltable.php",
data:{'name':username,'date':curdate},
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
console.log(jsonData);
var timetabledata1 = new google.visualization.Table(document.getElementById('commontables'));
timetabledata1.draw(data, { 'backgroundColor':'transparent'});
}
My PHP Scritp to populate Data:
$colarray=array(array("id"=>"ent","label"=>"Entry_time","pattern"=>"","type"=>"datetime"),array('id'=>"ext","label"=>"Exit_time","pattern"=>"","type"=>"datetime"));
$table['cols']=$colarray;
for($i=0;$i<$customersnum;$i++)
{
$prefinal[$i]=array("c"=>array(array("v"=>$entry_time[$i]),array("v"=>$exit_time[$i])));
}
$table['rows']=$prefinal;
echo json_encode($table);