PHP Time Remaining in Current Day - php

How can we find out how many time remains to end the current day from current time[date('Y-m-d H:i:s')] in PHP.

For example with a combination of mktime() and time():
$left = mktime(23,59,59) - time() +1; // +1 adds the one second left to 00:00
Update:
From Simon's suggestion, mktime(24,0,0) works too:
$left = mktime(24,0,0) - time();

$time_in_seconds = (24*3600) - (date('H')*3600 + date('i')*60 + date('s'));
Calculates the total seconds of one day and subtracts the seconds passed until the current hour of the day.

In Javascript, for anyone interested (takes care of timezone differences) :
var now=new Date();
var d=new Date(now.getYear(),now.getMonth(),now.getDate(),23-now.getHours(),59-now.getMinutes(),59-now.getSeconds()+1,0);
document.write(checkTime(d.getHours()) + ':' + checkTime(d.getMinutes()) + ':' + checkTime(d.getSeconds()) + ' time left');
function checkTime(i) {
if (i<10)
{
i="0" + i;
}
return i;
}

Related

Jquery calculating time duration by giving start time and end time

I am using jQuery time picker to get start time and end time in 12hr format. I need to calculate time duration between start time and end time in HH:MM:SS format. I have the following code with me. But its returning duration like 1.1666. So what changes should I make in my code.
valueStart = $("#startTime").val();
valueStop = $("#endTime").val();
var diff = ( new Date("1970-1-1 " + valueStop) - new Date("1970-1-1 " + valueStart) ) / 1000 / 60 / 60;
var diffe = Math.abs(diff);
alert(diffe);
valueStart = $("#startTime").val();
valueStop = $("#endTime").val();
var str0="01/01/1970 " + valueStart;
var str1="01/01/1970 " + valueStop;
var diff=(Date.parse(str1)-Date.parse(str0))/1000/60;
var hours=String(100+Math.floor(diff/60)).substr(1);
var mins=String(100+diff%60).substr(1);
alert(hours+':'+mins);
Try it with xdate (javaScript Date Library)
try this if you want in HH:MM:SS format..
var diff =
new Date( '01/01/1970 ' + valueStop) -
new Date( '01/01/1970 ' + valueStart );
var sec_numb=(diff /1000)+"";
var hours = Math.floor(sec_numb / 3600);
var minutes = Math.floor((sec_numb - (hours * 3600)) / 60);
var seconds = sec_numb - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
alert(time);

Clock widgets in PHP

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>

How to get location based time?

i am working on javascript which displays time based on location, that is if a user logs on from china it should display their local time or a user from india it should display their code.No matter what, i am not able to get the code.pls someone help.
You can get the users local time in JS with:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")

Storing javascript Date() in mySQL

I currently have a javascript variable which records the current date and time like so:
var time_of_call;
time_of_call = new Date();
and I need to store it in a MySQL database. When I try to upload it, the column just appears blank but I'm not sure what I'm doing wrong. I know it's not a problem with the mysql query because I have tried entering different values and it works OK.
I have the column set to DATETIME and I am uploading the value unformatted. Could someone please explain what I need to do differently?
Thanks for any help
P.s. I can't use NOW() because I am using that to capture the time that the record is actually captured, and this time_of_call records the time a call actually comes in.
In JavaScript, the underlying value of a Date object is in milliseconds, while Unix servers (and MySQL internally) uses whole seconds.
To get the underlying value for a javascript date object:
var pDate = new Date();
var pDateSeconds = pDate.valueOf()/1000;
From here, you'll send it to the server... it is up to you whether or not to divide it by 1000, but it has to be done somewhere. From this value, you could just call something like PHP's date('Y-m-d H:i:s', $pDateSeconds); on it.
Or, you could just use the built-in function in MySQL:
$sql = 'UPDATE table_name
SET field_name=FROM_UNIXTIME('.$pDateSeconds.')
WHERE field_name='.$row_id;
You must convert your format. Also, you don't "upload" an object.
At least, you have to do: time_of_call.getTime(); which returns a timestamp.
After uploading a timestamp, you have to convert to the DB's native format, eg: date('d-m-Y',(int)$_REQUEST['time_of_call']);
The date format depends on whether you used DATE, DATETIME, TIME, TIMESTAMP or INT.
If you used either TIMESTAMP or INT (which is best IMHO), you don't need any conversion.
Important: A javascript timestamp is in milliseconds, whereas a PHP timestamp is in seconds.
You will have to do time=time_of_call.getTime()/1000; to fix this.
Afaik Date doesn't add leading zero's to the day and month you should format the date like this:
yyyy-mm-dd hh:mm:ss
To get the expected result you could use a function:
Javascript:
function formatDate(date1) {
return date1.getFullYear() + '-' +
(date1.getMonth() < 9 ? '0' : '') + (date1.getMonth()+1) + '-' +
(date1.getDate() < 10 ? '0' : '') + date1.getDate();
}
You could use either of these to add a method for getting SQL formatted timestamps from a JS Date object.
First in user's local time:
Date.prototype.getTimestamp = function() {
var year = this.getFullYear(),
month = this.getMonth(),
day = this.getDate(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}
var d = new Date();
console.log(d.getTimestamp());
Second in UTC:
Date.prototype.getUTCTimestamp = function() {
var year = this.getUTCFullYear(),
month = this.getUTCMonth(),
day = this.getUTCDate(),
hours = this.getUTCHours(),
minutes = this.getUTCMinutes(),
seconds = this.getUTCSeconds();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}
var d = new Date();
console.log(d.getUTCTimestamp());
I've created a lightweight script that extends the Date object with these and other commonly needed here: https://github.com/rtuosto/js-date-format
You need to add date with correct format, which is: YYYY-MM-DD HH:MM:SS. 10.3.1. The DATETIME, DATE, and TIMESTAMP Types
So to convert that you need to write something like this:
var t = new Date();
var YYYY = t.getFullYear();
var MM = ((t.getMonth() + 1 < 10) ? '0' : '') + (t.getMonth() + 1);
var DD = ((t.getDate() < 10) ? '0' : '') + t.getDate();
var HH = ((t.getHours() < 10) ? '0' : '') + t.getHours();
var mm = ((t.getMinutes() < 10) ? '0' : '') + t.getMinutes();
var ss = ((t.getSeconds() < 10) ? '0' : '') + t.getSeconds();
var time_of_call = YYYY+'-'+MM+'-'+DD+' '+HH+':'+mm+':'+ss;
Of course you can shorten all this and stuff like that, but you get the idea.
Try This:
Quick Java Script Date function :-)
/***************************************************
* Function for Fetch Date, Day, Time, Month etc..
* input #param = month, date, time, mysql_date etc..
**************************************************/
function getDateNow(output) {
var dateObj = new Date();
var dateString = dateObj.toString();
dateArray = dateString.split(” “);
if (output == ‘day’) {
output = dateArray[0];
} else if (output == ‘month’) {
output = dateArray[1];
} else if (output == ‘date’) {
output = dateArray[2];
} else if (output == ‘year’) {
output = dateArray[3];
} else if (output == ‘time’) {
output = dateArray[4];
} else if (output == ‘am_pm’) {
output = dateArray[5];
} else if (output == ‘mysql_date’) {
var dt = new Date();
output = dt.toYMD();
}else {
output = dateArray[6];
}
return output;
}
/*****************************************************
* Function for Fetch date like MySQL date fromat
* type #Prototype
****************************************************/
(function() {
Date.prototype.toYMD = Date_toYMD;
function Date_toYMD() {
var year, month, day;
year = String(this.getFullYear());
month = String(this.getMonth() + 1);
if (month.length == 1) {
month = “0″ + month;
}
day = String(this.getDate());
if (day.length == 1) {
day = “0″ + day;
}
return year + “-” + month + “-” + day;
}
})();
/***********************************
* How to Use Function with JavaScript
**********************************/
var sqlDate = getDateNow(‘mysql_date’));
/***********************************
* How to Use Function with HTML
**********************************/
<a href=”javascript:void(0);” onClick=”this.innerHTML = getDateNow(‘mysql_date’);” title=”click to know Date as SQL Date”>JavaScript Date to MySQL Date</a>
I found a snippet a while back, which may help depending on where you want to convert:
function formatDate(date1) {
return date1.getFullYear() + '-' +
(date1.getMonth() < 9 ? '0' : '') + (date1.getMonth()+1) + '-' +
(date1.getDate() < 10 ? '0' : '') + date1.getDate();
}

How can I get the user's local time instead of the server's time?

How can I get the time of the client side?
When I use date() it returns server's time.
Here's a "PHP" solution:
echo '<script type="text/javascript">
var x = new Date()
document.write(x)
</script>';
As mentioned by everyone PHP only displays server side time.
For client side, you would need Javascript, something like the following should do the trick.
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
document.write("<b>" + hours + ":" + minutes + " " + "</b>");
And if you want the AM/PM suffix, something like the following should work:
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>");
Here is a list of additional JavaScript Date and Time functions you could mess around with.
You could possibly use Geolocation by IP Address to work out which country the user is in, and then use that.
But using Javascript or letting the user choose a Timezone will probably be better.
As PHP runs on the server-side, you cannot access the client-side time from PHP : PHP doesn't know much about the browser -- and you can have PHP scripts that run without being called from a browser.
But you could get it from Javascript (which is executed on the client-side), and, then, pass it to PHP via an Ajax request, for example.
And here are a couple of questions+answers that might help you getting started :
Automatically detect user’s current local time with JavaScript or PHP
How can I determine a web user’s time zone?
PHP is server side only as far as i know.
You maybe want to use JavaScript.
As other's have mentioned, you can use Geo Location Services based on the IP Address.
I found it to be off by about 18 seconds due to IP location accuracy, by using a $responseTime offset it helped me narrow it down to 2 second accuracy in the Viewers Location.
<?php;
echo deviceTime('D, M d Y h:i:s a');
function deviceTime($dateFormatString)
{
$responseTime = 21;
$ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"])?$_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']);
$ch = file_get_contents('https://ipapi.co/'.$viewersIP.'/json/');
$ipParts = json_decode($ch,true);
$timezone = $ipParts['timezone'];
$date = new DateTime(date('m/d/Y h:i:s a', time()+$responseTime));
$date->setTimezone(new DateTimeZone($timezone));
return $date->format($dateFormatString);
}
?>

Categories