setInterval(function(){
var ss = "<?php echo Date('Y-m-d H:i:s'); ?>";
console.log(ss);
}, 1000);
I have this little code. It takes Date one time and then all the time, result is the same.
(12) 2014-10-19 19:42:54
How can I fix it?
If you're trying to have a clock that increases by the second just like any other clock, you're gonna have to use javascript to implement it and you generally don't even need PHP to do it.
Edited answer to use server time
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
var today=new Date('<?php print date("F d, Y H:i:s", time())?>');
function setTime() {
today.setSeconds(today.getSeconds()+1)
var year=today.getFullYear();
var month=today.getMonth();
var day=today.getDate();
var hour=today.getHours();
var minute=today.getMinutes();
var second=today.getSeconds();
minute = checkTime(minute);
second = checkTime(second);
month = checkTime(month);
var time = year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
console.log(time);
}
setInterval(startTime, 1000);
Try this:
var unixtime = <?=date('U')?>;
setInterval(function()
{
var date = new Date();
date.setTime(++unixtime * 1000);
var ss = date.getFullYear() + '-'
+ (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
+ (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
+ (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
+ (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
console.log(ss);
}, 1000);
Open rendered page source and you will see that resulted HTML looks something like this:
<script>
setInterval(function(){
var ss = "2014-10-19 20:52:12";
console.log(ss);
}, 1000);
</script>
PHP script is a server side program that outputs some HTML, which browser renders. So there is no surprise that you are facing this behavior.
If you want to create a timer in javasctipt you need to use Date object instance:
setInterval(function() {
var d = new Date(),
ss = d.getFullYear() + '-' + d.getMonth(); // etc.. formate you date
console.log(ss);
}, 1000);
Refer Date documentation for available methods.
You have to update your date in JavaScript in each setInterval call.
When you produce static code using php it defines JavaScript function with fixed value of date. Body of this function isn't overrided after each call, because there is generated specific date.
Related
How I can display may full date in HTML?
Below, I have a basic function that displays the time which looks something like this: xxxx-x-x xx:xx:x
Also, my current output is console.log, but I'm wondering how you would do it to get some ideas.
function time() {
var date = new Date();
var str = date.getFullYear() + '-' + (date.getMonth() + 1)
+ '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
return str;
}
console.log(time());
You can use toLocaleString() for that
function time() {
var date = new Date();
return date.toLocaleString();
}
console.log(time());
const dateText = document.createElement('span');
span.innerText = time();
document.appendChild(span);
// or
document.write(time());
you can use moment.js for this.:
check sample code here
let myDate = moment().format('YYYY-MM-DD hh:mm:ss',new Date());
further reads:
https://momentjs.com/
Please use this.
setInterval(() => {
document.body.innerHTML = '<p>'+time()+'</p>';
}, 1000);
You can change "document.body.innerHTML" as you wanted.
eg "document.getElementById("time").innerHTML"
I have to get Browser Local date and time with Javascript and compare it in PHP IF statement with value from database on page load to determine if product expired or not. How do I solve the issue without using cookies and or sessions?
Javascript
<script>
var currentDate = new Date(),
day = ('0' + (currentDate.getDate()+1)).slice(-2),
month = ('0' + (currentDate.getMonth()+1)).slice(-2),
year = currentDate.getFullYear();
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
document.write(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes)
</script>
PHP
if(strtotime( date and time from SCRIPT ) < strtotime($events date and time exiptation as $events_total_SKU[$e]['sales_end']))
{
print(" OK ");
.... and shopping cart code
}
else{
print(" Expired ");
}
You should store both the dates in JavaScript variables as below. And compare it in Js as well.
var currentDate = new Date(),
day = ('0' + (currentDate.getDate()+1)).slice(-2),
month = ('0' + (currentDate.getMonth()+1)).slice(-2),
year = currentDate.getFullYear();
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
var frontendDate = year + '-' + month + '-' +day + ' ' + hours + ':' + minutes;
var backednDateString = "<?php echo $events_total_SKU[$e]['sales_end'];?>";
// As backedn date is string convert it as date first.
var backednDateS = new Date(backednDateString );
if(frontendDate < backednDate)
{
alert(" OK ");
}
else{
alert(" Expired ");
}
Make sure format of both the dates are same.
What I want it is to get the output of the current time with Javascript. The output should be something similar as:
15:28:30 PM
And I got this using the following code:
var date = new Date();
document.write("Current time: " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
if (date.getHours() <= 12)
document.write(" AM");
else
document.write(" PM");
So the output that I get it is:
Current time: 3:0:16 AM
But I want to know if there is some faster or cleaner solution to solve this problem because I think my solution it is not good at all.
Is it possible to get the same behaviour with a better method or solution?
Thanks in advance!
var date = new Date();
var time = date.toLocaleString('en').split(', ').pop();
This will give you the exact format you are looking for. Although I would go with a library like Moment.js or Date.js. Tons of options with those.
It's like this:
var dt = new Date;
console.log(dt.toLocaleTimeString());
I see nothing wrong with your approach. However, if you want the flexibility of different formats, there's a library called moment.js which allows you to build and format dates.
moment().format('hh:mm:ss A'); // 12:00:00 AM
I think that you make right way. Only need modify a little to get your expectation:
var date = new Date();
int hour = date.getHours();
string abbr;
if (date.getHours() <= 12)
abbr = " AM";
else {
hour = hour + 12;
abbr = " PM";
}
document.write("Current time: " + hour + ":" + date.getMinutes() + ":" + date.getSeconds() + abbr);
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
Found this thread
I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()
I'm writing a shortcut JavaScript file to make $date and $time variables. It should work as far as I can tell, but it won't display and Google Chrome's debugger shows a [Uncaught TypeError: Cannot Read 'firstChild' of null]
Here's my code:
function mdy(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = month + "/" + day + "/" + year;
document.getElementById('mdy').firstChild.nodeValue = string;
}
function ymd(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = year + "/" + month + "/" + day;
document.getElementById('ymd').firstChild.nodeValue = string;
}
var $date = {
mdy: '<span id="mdy"> </span>',
ymd: '<span id="ymd"> </span>'
}
/* $time module */
// this comes in two formats, standard and military.
// type $time.standard for standard time and $time.military
// for military time
function tstandard(){
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
var diem = ( hours < 12 ) ? "am" : "pm";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
var string = hours + ":" + minutes + " " + diem;
document.getElementById("tstandard").firstChild.nodeValue = string;
}
function tmilitary() {
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
hours = ( hours == 0 ) ? 12 : hours;
if(hours < 10) { hours = "0" + hours }
var string = hours + ":" + minutes;
document.getElementById("tmilitary").firstChild.nodeValue = string;
}
var $time = {
standard: "<span id='tstandard'> </span>",
military: "<span id='tmilitary'> </span>"
}
/*! universal body onload function !*/
window.onload = function(){
mdy(); setInterval('mdy()', 1000);
ymd(); setInterval('ymd()', 1000);
tstandard(); setInterval('tstandard()', 1000);
tmilitary(); setInterval('tmilitary()', 1000);
}
And in my HTML, I'm doing:
<script>document.write($date.mdy + " - " + $time.standard);</script>
You are adding two placeholder elements to the DOM – <span id="ymd"></span> and <span id="tstandard">.
Then, in the window.onload handler, you are trying to update contents of not only these two placeholders but also of two other elements which are not in the DOM (id="ymd" and id="tmilitary"). The document.getElementById('ymd') (and 'tmilitary') call correctly returns undefined because of that fact.
You want to remove the calls to the ymd and tmilitary functions.
window.onload = function(){
mdy();
setInterval(mdy, 1000);
tstandard();
setInterval(tstandard, 1000);
};
I also changed the calls to setInterval to simplify things. Passing references is more efficient and clear.
I think you might want this:
document.getElementById('mdy').innerHTML = string;
or this:
document.getElementById('mdy').nodeValue = string;
instead of this:
document.getElementById('mdy').firstChild.nodeValue = string;
That should take care of the errors. (There's no need to get the firstChild from a getElementById call, it already returns a node by default.)