Hello I need to spend a given XML through javascript to subtract the current date and time date.
What makes this code is to show the remaining time of a song streaming in minutes and seconds
And then with javascript parsing date and I transform in milliseconds and the current date will also rest in ms.
In Chrome date shows me perfectly, but in Mozilla and IE NaN console shows me and gives error.
I do not understand is that if I have parsed the date because it only works in Chrome. There must be a mistake.
PHP (I draw the start date of a song)
<?php
$xml = # simplexml_load_file('http://www.example.com');
foreach ($xml as $track){
$startTime = $track->starttime;
$songDuration = $track->playduration;
}
?>
JAVASCRIPT:
var spend javascript
var tiempoComienzo= "<?php echo $startTime ?>";
var cancionDuracion="<?php echo $songDuration ?>";
//parse delivered date from php
var d = new Date(Date.parse(tiempoComienzo));
//PHP get the date in milliseconds
var resultPHPms = d.getTime();
//get the current date
var f = new Date();
//step the current date to milliseconds
var resultJSms = f.getTime();
//adding the date of the song to the length of the song
var inicioMasCancion=parseInt(cancionDuracion) + parseInt(resultPHPms);
//It is the challenge to the current date
var TiempoRestante=inicioMasCancion-parseInt(resultJSms);
//pass the result to seconds
seconds=(TiempoRestante/1000)
var container = document.getElementById('time');
var seconds = parseInt(seconds+7);
//step seconds to minutes and seconds
var minutes = parseInt( seconds / 60 ) % 60;
var seconds = seconds % 60;
var contadorDeTiempo=(minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
countdown(seconds);
function countdown:
<script>
var timer;
function countdown(seconds) {
seconds--;
if(seconds >= -1) {
container.innerHTML =contadorDeTiempo;
}
}
timer = setInterval(countdown, 1000);
</script>
HTML:
<span id='time'></span>
In chrome it is perfectly displayed and works perfect. But in Mozilla and IE console NaN it is shown, specifically in this line:
var d = new Date(Date.parse(tiempoComienzo));
How I could solve? The resulting XML date is as follows:
2015-12-20 12:45:33.17
thanks very much for your help
Related
This project includes creating a form for users to enter the start and end time of a promotion. The site where the promotion will be live operates in the Pacific Time Zone and the user creating the promotion could be anywhere in the world.
The start time must be one hour greater than the current PST (or PDT depending on season). The current method of validating the start time is not working because it pulls the local time of the user's computer.
I need a way to compare the user's local time to Pacific Time and validate that the promotional start time is one hour greater.
My working theory is to find the offset between the user's local time and GMT time, then find the offset between current Pacific time and GMT (which varies by 7 or 8 hours depending on DST--right?), then apply these offsets to the user's time and compare to Pacific time plus one hour.
I have succeeded in finding the necessary offsets and alerting the correct current time in Pacific time in various strings and timestamps but the overall logic escapes me. Also, I have been unable to successfully add one hour to a TimeStamp.
this question is similar, and many others, but in this case the OP has a fixed offset:
Compare user's time zone with the website's office location time zone
Current code:
function valid() {
var starttime=$('#1-PromotionalSaleStartTime').val();
var endtime=$('#1-PromotionalSaleEndTime').val();
var now = new Date();
var hour= now.getHours();
var min = now.getMinutes()+10;
var nows= parseInt(hour)+1;
var time=nows+':'+min;
var presentime = now.getHours()+':'+now.getMinutes()
var month =now.getMonth()+1;
var day = now.getDate();
var output = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+time;
var now = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+presentime;
var present = new Date(now);
var oneDay = 24*60*60*1000; // hours*min*sec*milliseconds
var firstDate = new Date(starttime);
var secondDate = new Date(endtime);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
var diff = Math.round(Math.abs(( present.getTime() - firstDate.getTime())/(oneDay)));
var presentTimeStamp = +'<?php echo time(); ?>' * 1000;
var firstDateTimeStamp = Date.parse($('#1-PromotionalSaleStartTime').val());
var err = 0;
<?php if($this->add!="" && isset($this->add)) {?>
if(presentTimeStamp > firstDateTimeStamp) {
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>');
err++;
}
<?php } ?>
if(diffDays==0){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>The date difference between Start and End dates should be 24 hours.</li></ul>');
err++;
}
if(starttime < output){
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Your Start time should be at least 1 hour more than the current Pacific Time like. '+ output +'</li></ul>');
err++;
}
if((Date.parse(starttime)> Date.parse(endtime)) ){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>End Time cannot be less than Start Time plus 1 day.</li></ul>');
err++;
}
Try this on the Server side:
/* timetest.php */
<?php
if(isset($_POST['dateInfo'])){
date_default_timezone_set('America/Los_Angeles'); $data = array();
$dt = new DateTime;
$pacificPlusOneOffset = dt->add(new DateInterval('P1D'))->getOffset();
$data['diff'] = +$_POST['dateInfo']-$pacificPlusOneOffset;
echo json_encode($data);
}
else{
// could be some kind of hack
}
?>
AJAX should send JavaScript on the Client side, like:
var pre = onload;
onload = function(){
if(pre)pre();
// more code to run other code here
function post(url, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s;
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); x.open('POST', url);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', s.length);
x.setRequestHeader('Connection', 'close');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200 && success){
success(eval('('+x.responseText+')'));
}
}
x.send(s);
}
post('timetest.php', {dateInfo:new Date().getTimezoneOffset()}, function(result){
console.log(result.diff);
})
}
I am trying to create a Javascript clock that will display the current Actual time, rather than displaying the local time of the client machine.
The clock is part of a script which calculates the difference in time between two values (in php but the purpose of this clock is to give a visual representation). It is important that the user of the script cannot change the time that is displayed as this will produce incorrect results for the outcome of the whole program.
I realise that i may have to use a php function to return the time in a particular time zone but i do not understand how to input this into my script. My Javascript clock code is below (currenttime_large is the ID of the DIV container of this script) :
<script type="text/javascript" language="javascript">
function renderTime() {
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('currenttime_large');
myClock.textContent = h + ":" + m + ":" + s + " ";
myClock.innerText = h + ":" + m + ":" + s + " ";
}
renderTime();
</script>
Please could someone advise how this script can be adjusted so that the clock which is displayed, displays GMT(London) time rather than the client time.
Many thanks in advance,
Aidan
Use the getUTC... methods:
var h = currentTime.getUTCHours();
var m = currentTime.getUTCMinutes();
var s = currentTime.getUTCSeconds();
I've been looking over something like this,
The best solution I've found is this
http://www.jqueryscript.net/demo/jQuery-Based-Analog-And-Digital-World-Clock-jClocksGMT-js/
If you want you can save the whole page, or download necessary files if they not saved automatically. Then in your html code you just change the GMT timezone according to ID.
That's it
I was searching of world analog clock. i found one source/example which is basically cretated with jQuery, Html 5, CSS 3 and canvas.
Source : https://github.com/php-dedicated-developers/world-clock
It can be done without PHP. I ve done it using simple HTML and JavaScript calculations.
Note: This clock IS NOT UNIVERSAL.
Because i live in india, i fixed all parameters according to Indian GMT (5:30).
If someone wants to use it who does not live in India will have to customize parameters according their own country GMT
How my code works? Here is your answer
First we have created a simple timer program.
Passed the time argument to a function called london()
3.in function london() everything is processed. I have put GMT of India. using the parameters function london is producing correct London time from Indian time and given GMT time
Note:
1. As this code is not universal.. people out of India will have to customize it as they want...
2.This code uses device time and processes correct GMT 0 time. Example my code works substracting 5 hours and 30 minutes from device time because my GMT is 5:30 (India)
3.Will work fine offline
4.If someone changes country(GMT) they will have to customize code again
Full Code
<body onload="timer()">
<p id="txt1"></p>
<p id="txt2"></p>
<script>
function timer(){
//Getting Device Time
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//Returning value of ckeckTime();
m = checkTime(m);
h = checkTime(h);
s = checkTime(s);
var trigger = setTimeout(timer,1000);
document.getElementById("txt1").innerHTML = h+" "+m+" "+s;
london(h,m,s); //Passing device time to function london
}
function london(h,m,s){
//This function produces london time
//var h (Device hour)
// m (Device minute)
// s (Device second)
defhr = 5; //define hour
defmn = 30; //define minutes
/* defhr = 5 and defmn = 30 according to India GMT +5 30*/
if(m < defmn){ //When device minute is less than define minutes
defhr += +0
var hour = h - defhr;
let x = m - defmn;
var min = 60 + x;
} else {
defhr += -1
var hour = h - defhr;
var min = m - defmn;
}
if(h < defhr){ //When device hour is less than define hour
let y = defhr - h;
var hour = 24 - y;
}else {
var hour = h - defhr;
}
// returning value of checkTime();
hour = checkTime(hour);
min = checkTime(min);
document.getElementById("txt2").innerHTML = hour+" "+min+" "+s;
}
//checkTime function adds 0 in front a number when it is less than 10
function checkTime(i){
if(i<10){ i="0"+i; }
return i;
}
</script>
</body>
</html>
Tip:
1. If you live in western countries or GMT value is negative then put negative value in defhr and defmn section.
If anyone is using this code in GMT + 5:30 (India)
They will not need customization.
Make sure your code is producing correct London GMT time.. Grab notebook,calculator or you can test it with online world clock too
I'm converting a PHP timestamp into a human readable form in javascript:
<script type="text/javascript">
var timeleft = new Date( <?php echo $lefttime; ?> * 1000 );
var hours = timeleft.getHours();
var minutes = timeleft.getMinutes();
var seconds = timeleft.getSeconds();
var countdown = function() {
console.log( "You have " + hours + ":" + minutes + ":" + seconds + " seconds left" );
</script>
The minutes and seconds work but I'm getting strange results for the hours. For example:
Timestamp: 1976
Function returns: 19:32:56
Any ideas why I'm getting "19" from .getHours() ?
I'm going to hazard a guess that you're in Eastern Time. What you are seeing is $lefttime seconds after the epoch, which in the case of EST is 7PM.
To fix it, just use basic math:
var timeleft = <?php echo $lefttime; ?>;
var hours = Math.floor(timeleft/3600);
var minutes = Math.floor(timeleft/60)%60;
var seconds = timeleft%60;
I need to show system date in my web site through wordpress in PHP.
it shows system time one time but not updating as days gone passed.
I need to change it according to my system date
You can't show your system time using PHP. If you want to show your system time you just need to use javascript.
try this,
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
Update:
If you want to show everything, please try this.
<script type="text/javascript">
document.write(new Date());
</script>
i have a question about a javascript/php cron issue. well its not an issue per se but in my case it is.
i have the below javascript that sets a cookie and counts down till the end of that cookie's time. in my case its 10 minutes.
I also have a cron file that runs every 10 minutes.
I would like to synchronize the countdown with the cron file.
The below script works well when i call it from the page however it counts down from the time the user visits the page and its out of sync with the cron file im running.
i understand this is not a php question but the pages im displaying the scripts are php.
Any pointers for me?
Help would be greatly appreciated.
Thank you for reading.
All i have is below.
<div id="countre4">
<script type="text/javascript">
function setCookie(c_name, value)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + 14);
var c_value = escape(value) + "; expires=" + exdate.toUTCString();
document.cookie = c_name + "=" + c_value;
}
function mycountre(countdownId, countdownTarget, countdownSeconds, countdownLooping){
var countre = document.getElementById(countdownId); // get html element
if (!countre) {
return;
}
var target = countdownTarget; // target time
var intervalId; // id of the interval
setCookie("time", target);
// update function
function updatecountre(){
var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
if (time < 0) { // if countdown ends
if (countdownLooping) { // if it should loop
target += 1000 * countdownSeconds; // set new target time
time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
setCookie("time", target);
} else { // otherwise
clearInterval(intervalId); // clear interval
time = 0; // set time to 0 to avoid displaying negative values
}
}
// split time to seconds, minutes and hours
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
// make string from splited values
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
countre.innerHTML = str;
}
intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
var parts = document.cookie.split(';');
var cookie = new Date().getTime() + 1000 * 15 * 60;
for (var i = 0; i < parts.length; ++i) {
if (parts[i].trim().indexOf('time') == 0) {
var value = parts[i].trim().split('=');
cookie = parseInt(value[1]);
}
}
mycountre(
'countre4', // id of the html element
cookie,
10 * 60, // time in seconds (10min here)
true // loop after countdown ends?
);
</script>
</div>
Maybe you should rethink your approach. Don't use a cookie for a piece of information actually stored on the server.
How about instead of a cookie, each PHP page simply set a global JS variable for how much time you have left. Something sorta like this:
<script>
var timeLeft = <? echo $timeLeftInMilliseconds ?>;
startCounter(timeleft);
</script>
Then your counter script can read that and animate a counter accordingly. This leaves it up to your server side code to accurately deliver when the next cron will happen.