Javascript countdown doesn't work in Safari or IE - javascript

This function works in Chrome, but not on IE or Safari, what am I doing wrong?
function countdown(){
var dDay = new Date().getUTCDate() + 1;
var dMonth = new Date().getUTCMonth() + 1;
var dYear = new Date().getUTCFullYear();
var BigDay = new Date(dYear+ ", " +dMonth+ ", " +dDay+ ",00:00:00");
var msPerDay = 24 * 60 * 60 * 1000;
var today = new Date();
var timeLeft = (BigDay.getTime() - today.getTime());
var e_daysLeft = timeLeft / msPerDay;
var daysLeft = Math.floor(e_daysLeft);
var e_hrsLeft = (e_daysLeft - daysLeft)*24;
var hrsLeft = Math.floor(e_hrsLeft);
var e_minsLeft = (e_hrsLeft - hrsLeft)*60;
var minsLeft = Math.floor(e_minsLeft);
var e_secsLeft = (e_minsLeft - minsLeft)*60;
var secsLeft = Math.floor(e_secsLeft);
if(daysLeft.toString().length === 1){
daysLeft = "0"+daysLeft;
}
if(hrsLeft.toString().length === 1){
hrsLeft = "0"+hrsLeft;
}
if(minsLeft.toString().length === 1){
minsLeft = "0"+minsLeft;
}
if(secsLeft.toString().length === 1){
secsLeft = "0"+secsLeft;
}
timeString = daysLeft + ":" + hrsLeft + ":" + minsLeft + ":" + secsLeft;
return timeString;
}
I use this to print the counter
window.setInterval(function(){
$('#countdown').html("Time left: "+ countdown());
}, 1000);
This is the result i get in Chrome:
Time left: 00:01:55:15
And this is the result i get in IE and Safari:
Time left: NaN:NaN:NaN:NaN

I think is because you are building an invalid date object in:
var BigDay = new Date(dYear+ ", " +dMonth+ ", " +dDay+ ",00:00:00");
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
A month is represented:
Integer value representing the month, beginning with 0 for January to
11 for December.
You only want to add a day to today, so try change your code in:
var BigDay = new Date();
BigDay.setDate(BigDay.getDate() + 1);
BigDay.setHours(0, 0, 0, 0);
Demo: http://jsfiddle.net/IrvinDominin/HgUhq/

Related

Problem in creating an alarm in Typescript but the alarm isn't working

I am creating an alarm clock using typescript and I am facing in issue. I am not being alarmed when the time passes.
I have taken three inputs from the HTML page – Hours, Minutes and Seconds.
After that I added them and subtracted the current time.
let h = <HTMLInputElement>document.getElementById("h");//getting input values of hour and ...
let m = <HTMLInputElement>document.getElementById("m");
let s = <HTMLInputElement>document.getElementById("s");
let h1 = parseFloat(h.value);//converting the input values from string to float
let m1 = parseFloat(m.value);
let s1 = parseFloat(s.value);
var rHours = new Date().getHours();
var rMinutes = new Date().getMinutes();
var rSeconds = new Date().getMinutes();
var calc = (h1) + (m1) + (s1) - rHours - rMinutes - rSeconds;
if(calc<=0){
alert("Alarm");
}
}
But it does not work properly.
I've haven't built a countdown timer in a while, so I thought I'ddo it for fun. This isn't especially Typescript, but it does run just fine in the compiler (see link below). It's regular JS so it will run in the snippet as well. I thought it might help you see how a countdown timer would work. Your code didn't reflect any kind of countdown, and your method of determining elapsed time was incorrect.
For the purposes of the demo, I set h1, m1 and s1 to dynamically be 1 minute from whenever the snippet is run. You can easily adapt this to work from your input elements.
document.querySelector('p span').innerHTML = new Date().toString()
function startCountdown() {
/* In your code uncomment this section...
let el_h = <HTMLInputElement>document.getElementById("h");
let el_m = <HTMLInputElement>document.getElementById("m");
let el_s = <HTMLInputElement>document.getElementById("s");
*/
// in your code comment out these lines and use yours from above instead (for typescript typing)
let el_h = document.getElementById("h");
let el_m = document.getElementById("m");
let el_s = document.getElementById("s");
let h1 = parseFloat(el_h.value);
let m1 = parseFloat(el_m.value);
let s1 = parseFloat(el_s.value);
//const [h1, m1, s1] = ( (new Date().getHours() ) + ":" + (new Date().getMinutes() + 2) + ":" + new Date().getSeconds()).split(":");
// get todays date
let today = new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate();
// add on the hours from the inputs
today += " " + h1 + ":" + m1 + ":" + s1;
const myTime = new Date(today);
console.log('countdown to:', myTime, 'from:', new Date());
const interval = setInterval(() => {
let diff = (myTime.getTime() - new Date().getTime()) / 1000; // seconds
let h = Math.floor(diff / 3600);
let m = Math.floor(diff / 60 % 60);
let s = Math.floor(diff % 60)
console.log(h + " hours, " + m + " minutes, " + s + " seconds")
if (diff <= 0) {
clearInterval(interval);
console.log("ALARM");
}
}, 1000)
}
<p>Cur time: <span></span></p>
<input id='h' placeholder='Hour (military time)'><input id='m' placeholder='Minute'><input id='s' placeholder='Seconds'><button onclick='startCountdown()'>Start</button>
tsplayground link
document.querySelector('p span').innerHTML = new Date().toString()
function startCountdown() {
/* In your code uncomment this section...
let el_h = <HTMLInputElement>document.getElementById("h");
let el_m = <HTMLInputElement>document.getElementById("m");
let el_s = <HTMLInputElement>document.getElementById("s");
*/
// in your code comment out these lines and use yours from above instead (for typescript typing)
let el_h = document.getElementById("h");
let el_m = document.getElementById("m");
let el_s = document.getElementById("s");
let h1 = parseFloat(el_h.value);
let m1 = parseFloat(el_m.value);
let s1 = parseFloat(el_s.value);
//const [h1, m1, s1] = ( (new Date().getHours() ) + ":" + (new Date().getMinutes() + 2) + ":" + new Date().getSeconds()).split(":");
// get todays date
let today = new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate();
// add on the hours from the inputs
today += " " + h1 + ":" + m1 + ":" + s1;
const myTime = new Date(today);
console.log('countdown to:', myTime, 'from:', new Date());
const interval = setInterval(() => {
let diff = (myTime.getTime() - new Date().getTime()) / 1000; // seconds
let h = Math.floor(diff / 3600);
let m = Math.floor(diff / 60 % 60);
let s = Math.floor(diff % 60)
console.log(h + " hours, " + m + " minutes, " + s + " seconds")
if (diff <= 0) {
clearInterval(interval);
console.log("ALARM");
}
}, 1000)
}
<p>Cur time: <span></span></p>
<input id='h' placeholder='Hour (military time)'><input id='m' placeholder='Minute'><input id='s' placeholder='Seconds'><button onclick='startCountdown()'>Start</button>

Javascript Booking Calculator Not Counting 24 Hours As 1 Day

I've created a booking calculator by date using JavaScript.
Basically I want the base price to be £25 for 1 day (24 hours) or less, and £10 for each additional day (each additional 24 hours).
Below is the main part of the code.
jQuery(document).ready(function($) {
var prequote=25.00;
var taxa = 10.00;
var hoje = new Date();
hoje=hoje.getTime();
i = 0;
$('#quote').click(function(event) {
var d1= $('#d1').val();
var d2= $('#d2').val();
var t1= $('#t1').val();
var t2= $('#t2').val();
console.log(d1);
console.log(d2);
console.log(t1);
console.log(t2);
// end - start returns difference in milliseconds
var date2 = new Date(d2);
var date1 = new Date(d1);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = date2.getTime() - date1.getTime();
// get days
var d = millisBetween / millisecondsPerDay;
//alert ('value of days is:' +d);
//alert ( new Date("1970-1-1 " + t2) - new Date("1970-1-1 " + t1) ) / 1000 / 60 / 60;
var h= ( new Date("1970-1-1 " + t2) - new Date("1970-1-1 " + t1) ) / 1000 / 60 / 60;
//alert ('value of hours is:' +h);
t1 =t1.split(':');
t2 =t2.split(':');
var dat1 = d1.split("-");
var dd1 = dat1[2];
var mm1 = dat1[1];
var yy1 = dat1[0];
var hh1 = t1[0];
var ms1 = t1[1];
var dat2 = d2.split("-");
var dd2 = dat2[2];
var mm2 = dat2[1];
var yy2 = dat2[0];
var hh2 =t2[0];
var ms2 = t2[1];
var x1 = yy1 + ',' + mm1 + ',' + dd1 + ' ' + hh1 + ':' + ms1;
var x2 = yy2 + ',' + mm2 + ',' + dd2 + ' ' + hh2 + ':' + ms2;
var ent = dd1 + '/'+ mm1 +'/'+yy1+' '+ hh1 + ':' + ms1;
var ext = dd2 + '/'+ mm2 +'/'+yy2+' '+ hh2 + ':' + ms2;
var xi = yy1 + ',' + mm1 + ',' + dd1 ;
var xj = yy2 + ',' + mm2 + ',' + dd2 ;
var start =new Date(x1);
//var start_i =new Date(xi);
var end = new Date(x2);
// var end_i = new Date(xj);
start = start.getTime();
end= end.getTime();
if(start === end){
alert('Min rental days is 1');
}
else if(start < end){
// hh1 = parseInt(hh1);ms1 = parseInt(ms1);hh2 = parseInt(hh2);ms2 = parseInt(ms2);;
/*while(start_i < end_i){
i++;
var newDate = start_i.setDate(start_i.getDate() + 1);
start_i = new Date(newDate);
}*/
i=d;
if(i >= 1 ){
if(h > 0 ){
i=i+1;
}
prequote = prequote + (taxa * (i-2));
prequote = parseFloat(prequote.toFixed(2));
}
$('#en-tex').text(ent);
$('#ex-t').text(ext);
$('#prequote').html(prequote);
$('#modal-img').modal('show');
prequote=25.00;
$('#tupd').val(ent);
$('#tdod').val(ext);
}
else{
alert('Please fill in all the date and time fields.');
}
});
The 1st issue is, if I select for example Monday 21st at 9:00am to Tuesday 22nd at 9:00am it doesn't count the fee as for 24 hours. Only if the end date is AFTER 9:00am.
Likewise for longer dates, it only charges for a day AFTER 24 hours and not from 24 hours on the dot.
2nd issue is, if somebody selects less than 24 hours (i.e Monday 21st at 9:00am to Tuesday 22nd at 7:00am) it minuses the £10 from £25. I want it to still quote the base price of £25.
I advise you to use momentJS. Is pretty easy to use.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Or just like that:
var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');
console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4
Edit.:
Adding some ideas. You can just simply use the example of #jeff:
dt1 = new Date('2016-01-21 20:00:00');
dt2 = new Date('2016-01-24 09:00:00');
dif = dt2-dt1;
dif = dif / ( 1000 * 60 * 60 * 24 );
days = Math.ceil(dif);
var total = 0;
if (days > 0) {
total = 25 + ( (days-1) * 10 ) // total = <first day with prequote 25 and then others days are 10 bucks>
}
console.log(total); // total of amout to be paid
Maybe thia can solve your issue.
Since you are working with whole days you can simplify the process by:
dt1 = new Date('2016-01-21 09:00:00');
dt2 = new Date('2016-01-22 09:00:00');
dif = dt2-dt1;
dif = dif / ( 1000 * 60 * 60 * 24 );
days = Math.ceil(dif);
The days value contains a whole number for the amount of days between the two dates. Do your pricing from this value.
When some one rent room for less than 24 hour. Value of i is become negative. From your expression
prequote = prequote + (taxa * (i-2));
If i is smaller than 2. taxa variable become negative and you have get price less than 25. Please use this below line
i=(i<2)?i=2:i;
From above expression. Your value cannot be smaller than £25. Hope it helps you

add one day to date if it exceeded to a specific time in javascript

Here's my code for getting the time after adding specific time.. I don't know how to shift to tomorrow's date if the base_time is example: 4:50 PM and the 'default END TIME' is only 5:00 PM and I have to add 30 mins on the base_time. If I add 30 mins on the base, the final date/time is TOMORROW at 8:20 AM.. because the start of the day(work) is 8:00 AM.
Question : How to do this? e.g. January 3, 2016 04:50:00 PM + (00:30:00) = January 4, 2016 08:20:00 AM.
start time of work is at 8:00 AM
end is at 5:00 PM
Please help me on this. Thank you guys. I really need this.
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert){
var hms = timeToConvert;
var a = hms.split(':');
seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
// toSeconds("16:30:00");
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert("total seconds = " + total_seconds);
total_time = total_seconds;
total_seconds = 0;
if (total_time <= 61200) {
var date = new Date(null);
date.setSeconds(total_time);
var date1 = day + "-" + (month+1) + "-" + year + " " + date.toISOString().substr(11, 8);
}
else {
var da = new Date();
var day1 = Number(da.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = da.getMonth();
var year1 = da.getFullYear();
total_time -= 61200;
var new_time = 28800 + total_time; // Morning 8'o clock + remaining time
da.setSeconds(total_time);
var date1 = day1 + "-" + (month1+1) + "-" + year1 + " " + da.toISOString().substr(11, 8);
}
alert(date1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label><input id="acc1" type="checkbox" name="acc">acc 1</label><br>
<label><input id="acc2" type="checkbox" name="acc">acc 2</label><br>
<input type="button" class="btn btn-success" id="btn" name="btn" value="button">
edited and modified based on #Navaneethan answer. thank for that. But no I'm curious on how to consider the weekends? Those days without work. For example, Friday, the next day should be on Monday. The same for the changes in Months. How am I supposed to do that. Please help me. Thank you.
I just modified your code... Try this. It may work
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert) {
var hms = timeToConvert;
var a = hms.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert(total_seconds);
total_time = total_seconds;
total_seconds = 0;
var date = new Date();
if (total_time <= 61200) {
date.setSeconds(total_time);
var date1 = date.toISOString().substr(11, 8);
}
else {
var day1 = Number(date.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = date.getMonth();
var year1 = date.getFullYear();
total_time -= 61200;
var new_time = 28880 + total_time; //Morning 8'o clock + remaining time
date.setSeconds(total_time);
var date1 = day1 + "-" + month1 + "-" + year1 + ":" + date.toISOString().substr(11, 8);
}
alert(date1);
});

Get Days and hours from two dates in js

I am trying to get Days,hours from two dates.I searched for the solution and try some code like below but none of them returns the correct days with hours like 2 days ,3 hours.My fields values are like :
d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';
var dateDiff = function ( d1, d2 ) {
var diff = Math.abs(d1 - d2);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000) + " days";
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000) + " hours";
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000) + " minutes";
} else {
return "< 1 minute";
}
};
function DateDiff(date1, date2) {
var msMinute = 60*1000,
msDay = 60*60*24*1000,
c = new Date(), /* now */
d = new Date(c.getTime() + msDay - msMinute);
return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value
}
what am i doing wrong.Any help thanks
Have you converted d1, d2 to Date object before calling the function dateDiff? Because if you haven't, this line var diff = Math.abs(d1 - d2); won't work as expected.
UPDATE:
I'am assuming your d1 and d2 are in "Y-m-d H:S:M" format, try this:
function parseDate(str){
var tmp = str.split(' ');
var d = tmp[0].split('-');
var t = tmp[1].split(':');
return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}
function dateDiff(d1, d2){
d1 = parseDate(d1);
d2 = parseDate(d2);
// ...
// Your code continues
}
I wish I could make it simpler... But this seems to work.
var d1 = '2014-10-09 08:10:58',
d2 ='2015-10-09 08:10:50';
function getDateFromString(str) {
var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
values = regexDate.exec(str);
return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function dateDiff(d1,d2){
if (d1.getTime() > d2.getTime()) {
var oldD1 = d1;
d1 = d2;
d2 = oldD1;
}
var yearDiff = d2.getFullYear() - d1.getFullYear(),
monthDiff = d2.getMonth() - d1.getMonth(),
dayDiff = d2.getDate() - d1.getDate(),
hourDiff = d2.getHours() - d1.getHours(),
minDiff = d2.getMinutes() - d1.getMinutes(),
secDiff = d2.getSeconds() - d1.getSeconds();
if (secDiff < 0) {
secDiff = 60 + secDiff;
minDiff--;
}
if (minDiff < 0) {
minDiff = 60 + minDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff;
dayDiff--;
}
if (dayDiff < 0) {
var days = daysInMonth(date2.getMonth(), date2.getFullYear());
dayDiff = days + dayDiff;
monthDiff--;
}
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
var diff = yearDiff > 0 ? yearDiff + " years " : "";
diff += monthDiff > 0 ? monthDiff + " months " : "";
diff += dayDiff > 0 ? dayDiff + " days " : "";
diff += hourDiff > 0 ? hourDiff + " hours " : "";
diff += minDiff > 0 ? minDiff + " minutes " : "";
diff += secDiff > 0 ? secDiff + " seconds " : "";
return diff;
}
var date1 = getDateFromString(d1),
date2 = getDateFromString(d2)
document.getElementById('test').innerHTML += date1 + "<br />" + date2;
document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);
console.log(dateDiff(date1, date2));
See JSFiddle
It works in all browsers.
Try this - >
d1 = '2014-10-09 08:10:56';
d2 = '2014-11-09 10:10:56';
var diff = dateDiff(d1,d2);
alert(diff);
function splitDate(d1){
var dSplit = d1.split(' ');
d = dSplit[0] + 'T' + dSplit[1];
return d;
}
function dateDiff(d1,d2){
d1 = splitDate(d1);
d2 = splitDate(d2);
var date1 = new Date(d1);
var date2 = new Date(d2);
var dateDiff = new Date(date2 - date1);
var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
return diff;
}
I am assuming you want the difference between 2 dates.
var dateDiff = function(d1/*String*/, d2/*String*/){
var date1 = new Date(d1);
var date2 = new Date(d2);
var result = {
negative:false
};
var diff = date1-date2;
if(diff<0){
result.negative = true;
diff*=-1;
}
result.milliseconds = diff%1000;
diff-=result.milliseconds;
diff/=1000;
result.seconds = diff%60;
diff-=result.seconds
diff/=60;
result.minutes = diff%60;
diff-=result.minutes
diff/=60;
result.hours = diff%24;
diff-=result.hours
result.days= diff/=24;
//And so on
return result;
}
I'm not sure if I really understood but I think this is what you want : http://jsfiddle.net/OxyDesign/927n0L34/
JS
var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');
function toDaysAndHours(d1,d2){
var dif, hours, days, difString = '';
d1 = new Date(d1);
d2 = new Date(d2);
dif = Math.abs(d1 - d2);
hours = (dif/(1000*60*60)).toFixed(0);
days = (hours/24).toFixed(0);
hours = hours - days*24;
difString = days+' days, '+hours+' hours';
return difString;
}
In the first function you are using strings not dates. to properly initialize a date use the constructor, as in:
d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')
Then on d1 and d2 you can use all of the get*/set* methods specified here: http://www.w3schools.com/jsref/jsref_obj_date.asp
While I got distracted writing the answer, I see others have said similar things, but I will add this:
The data object approach is good for understanding things, but if you want to save time use http://momentjs.com/ or a similar module to save time and mistakes.

JS Time elapsed since a date

I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));

Categories

Resources