Storing javascript Date() in mySQL - php

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();
}

Related

compare user time zone (anywhere in the world) to current Pacific+one hour in PHP

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);
})
}

How to make a countdown timer that automatically restarts using PHP

I have a requirement to make a countdown timer that automatically restarts when the time has elapsed.
For example, I need to countdown from 3pm or 15:00 UK time and reset to start counting again when the time has reached.
I've been trying with some jQuery but that will show browser time and not server time. If anyone is able to share a solution please let me know.
Thanks in advance!
The code below is a working example from which works perfectly: https://gist.github.com/Majestik/3964527
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown() {
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Time remaining: <span id="countdownTimer"><span>00:00.<small>00</small></span>
In your PHP code when you are writing the HTML that includes this javascript file just set the variables there rather than getting javascript to do it once it has loaded, this way you are using your server time rather than the browser time.

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>

PHP Time Remaining in Current Day

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;
}

Categories