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);
Related
Beginner in web coding, I have issue to code a sharing button that lead to whatsapp and that share a countdown.
I achieve it with static string but I can't load a variable in it...
Does someone know where my issue is please ?
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 20, 2022 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var countdown_iam = days + "j " + hours + "h "
+ minutes + "m " + seconds + "s "
// Output the result in an element with id="countdown"
document.getElementById("countdown").innerHTML = countdown_iam;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "SURPRISE!!!";
}
}, 1000);
function openWhatsApp() {
//var countdown_whatsapp = "test";
//alert(countdown_iam);
window.open('whatsapp://send?text=' + countdown_iam);
}
</script>
<h2> WhatsApp sharing Link </h2>
<!-- create an image icon to open the WhatsApp onclick -->
<img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()">
Thank's for your help
The countdown_iam variable is created within a function and only exists within that function. So when the other function (openWhatsApp) tries to use the variable, it can't find it and the error occurs.
You want to access the countdown string from two different functions, so one option would be to create a new function that makes the countdown string and returns it. You can then call that function from both places. I've done that here:
<script>
function getCountdown() {
var countdownDate = new Date("Aug 20, 2022 12:00:00").getTime();
var now = new Date().getTime();
var distance = (countdownDate - now) / 1000;
if (distance < 0) {
return 'SURPRISE!!!';
} else {
var days = Math.floor(distance / (60 * 60 * 24));
var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor((distance % (60 * 60)) / 60);
var seconds = Math.floor(distance % 60);
return days + "j " + hours + "h " + minutes + "m " + seconds + "s ";
}
}
function openWhatsApp() {
alert('whatsapp://send?text=' + getCountdown());
}
setInterval(function() {
document.getElementById("countdown").innerHTML = getCountdown();
}, 1000);
</script>
<h2>WhatsApp Sharing Link</h2>
<p id="countdown"></p>
<p><img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()"></p>
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 need some help to code a script that counts down the days, hours, minutes and seconds from a unix timestamp.
timestamp is created with php
<? php echo hours ();?>
And I want the script to count down in real time with JavaScript.
Example
2 days, 3:15:39
Hope someone can help me a little:)
First you have some PHP errors. It should be e.g.
<?php echo time(); ?>
I'm using a timestamp in JavaScript for the ease of showing an example.
http://jsfiddle.net/pimvdb/AvXd3/
// the difference timestamp
var timestamp = (Date.now() + 1000 * 60 * 60 * 24 * 3) - Date.now();
timestamp /= 1000; // from ms to seconds
function component(x, v) {
return Math.floor(x / v);
}
var $div = $('div');
setInterval(function() { // execute code each second
timestamp--; // decrement timestamp with one second each second
var days = component(timestamp, 24 * 60 * 60), // calculate days from timestamp
hours = component(timestamp, 60 * 60) % 24, // hours
minutes = component(timestamp, 60) % 60, // minutes
seconds = component(timestamp, 1) % 60; // seconds
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); // display
}, 1000); // interval each second = 1000 ms
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();
}
My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>