I am creating an app in which I need to calculate the difference time between current time and previous time which will come from the database and need to display on list. The app works fine in India, but when the same app runs in US than difference time showing in -2560 seconds, or something like that. Why is this?
The code that I used to calculate the difference between times:
var timeAgoInWords = function(date) {
try {
var now = Math.ceil(Number(new Date()) / 1000),
dateTime = Math.ceil(Number(new Date(date)) / 1000),
diff = now - dateTime,
str;
if (diff < 60) {
return String(diff) + ' seconds ago';
} else if (diff < 3600) {
str = String(Math.ceil(diff / (60)));
return str + (str == "1" ? ' minute' : ' minutes') + ' ago';
} else if (diff < 86400) {
str = String(Math.ceil(diff / (3600)));
return str + (str == "1" ? ' hour' : ' hours') + ' ago';
} else if (diff < 60 * 60 * 24 * 365) {
str = String(Math.ceil(diff / (60 * 60 * 24)));
return str + (str == "1" ? ' day' : ' days') + ' ago';
} else {
return Ext.Date.format(new Date(date), 'jS M \'y');
}
} catch (e) {
return '';
}
};
The above function I am calling from an itemTpl, the below code is where CreatedDate will come from database which I save when a user submits a review comment and am passing as parameter to function.
this.posted(Ext.Date.parse(values.CreatedDate, "Y-m-d g:i:s"))
posted: timeAgoInWords
And here's how I store the current date and time into the database:
Ext.Date.patterns = { ISO8601Long: "Y-m-d H:i:s" };
var date = new Date();
var now = Ext.Date.format(date, Ext.Date.patterns['ISO8601Long'])
It is a timezone issue. Since the USA is behind IST, the date in seconds from epoch, is giving you a date in the past. This difference thus is negative, since the date you have entered still has to happen in the USA. It is recommend you change all times to UTC before you do any calculations for finding difference in times. You could also calculate the difference on your own server.
Related
I see that I various times like
01:45
//and
15:00
I assume that date is HH:MM in military ?
While have I seen some advanced functions then parse sentences and even some using the seconds like HH:MM:SS , I am wanting a simple and accurate way of getting the HH:MM
So I assume 15:00 is 3:00 ?
This function below is not going to work because I already have ":"
so below assumed HHMM right? when I believe I need HH:MM to be parsed ?
var getTravelTimeFormatted = function (str) {
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
Update
Ok, I assume that 15:00 is 3:00 , right?
So i stripped out the incoming ":" and then add it back
problem is the result is 25.0 so what does that mean?
var getTravelTimeFormatted = function (str) {
str = str.replace(/:/g,'');
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
console.log(getTravelTimeFormatted('15:00'));
Given a string HH:MM you can just split then subtract 12 hours. Here's a naive solution that doesn't check for invalid input.
function TwelveHourFormat(time) {
var dtParts = time.split(":");
var hours = dtParts[0];
var minutes = dtParts[1];
var suffix = "AM";
if (hours > 12) {
hours = hours - 12;
suffix = "PM";
}
else if (hours == "00") {
hours = 12;
suffix = "AM";
}
else if (hours == "12") {
suffix = "PM";
}
return (hours + ":" + minutes + " " + suffix);
}
This is a duplicate of Converting 24 hour time to 12 hour time w/ AM & PM using Javascript. Jasen's answer is fine, and more concise than the duplicate, but the function can be a little more concise:
/* Convert time in 24 hour hh:mm format to 12 hour h:mm ap format
** #param {string} time - in hh:mm format (e.g. 14:30)
** #returns {string} time in 12 hour format (e.g. 2:30 PM)
*/
function to12HourTime(time) {
var b = time.split(/\D/);
return (b[0]%12 || 12) + ':' + b[1] +
(b[0]<11? ' AM' : ' PM');
}
// Some tests
['23:15','2:15','03:15','00:30'].forEach(function(v) {
console.log(v + ' => ' + to12HourTime(v));
});
I have a digital clock that is running and it works great but I want to have multiple clocks running with different timezones. I am on the west coast and I would like the time to be different when people look at it in different timezones. How can I accomplish this?
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "AM";
if (hours > 12) {
hours = hours - 12;
meridiem = "PM";
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000);
});
To get the time in any timezone based on the current system time (which might be wrong, but that may not really matter), create a Date and just adjust the UTC time values by the required offset, then use UTC methods to build your formatted string.
e.g.
/* Return a time string in h:m:s a/p format
**
** #param {number} offsetInMinutes - offset of required timezone in minutes
** #returns {string} formatted time string
*/
function getTimeInZone(offsetInMinutes) {
function z(n) {return (n<10?'0':'') + n;}
var d = new Date();
d.setUTCMinutes(d.getUTCMinutes() + offsetInMinutes);
var h = d.getUTCHours();
return z(h%12||12) + ':' + z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' + (h<12? 'am' : 'pm');
}
// Time at UTC-08:00
document.write(getTimeInZone(-480));
You say you're "on the west coast", but not of where, so I'll assume USA where the likely timezone offset is UTC-08:00 (-480 minutes). So to always show the time in that timezone (with the usual caveat that the system clock may not be correct), you'd do:
getTimeInZone(-480);
Also note that innerText is a IE proprietary property and not supported in all browsers.
I am using the following code to get difference between two dates in hrs, minutes and seconds, which I will save later in database as a string field. So I was wondering if it is possible to use Moment.js library or any Javascript functionally in order to get the total number of hours, minutes and seconds for all date differences saved in the database (ex. 02:24:33 + 03:12:20 + 12:33:33) as one final HH:MM:SS taking in consideration that the HH could exceed 24 if the total number of hours summed exceeded 24? Thanks
$('.set-start-time').on("dp.change",function (e) {
$('.set-end-time').data("DateTimePicker").setMinDate(e.date);
});
$('.set-end-time').on("dp.change",function (e) {
$('.set-start-time').data("DateTimePicker").setMaxDate(e.date);
var now = $('.set-start-time').data('DateTimePicker').getDate().toLocaleString();
var then = $('.set-end-time').data('DateTimePicker').getDate().toLocaleString();
console.log(moment.utc(moment(then,"DD/MM/YYYY HH:mm:ss").diff(moment(now,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss"));
//Output here come in format ex. 02:42:33
});
It's probably too late for this to matter, but maybe something like this would help:
http://jsfiddle.net/8s8v3evf/8/
tl;dr
once you have your diff:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
function diffAsString(diff_ms) {
var hours = Math.floor(diff_ms / 3600000);
diff_ms -= (hours * 3600000);
var minutes = Math.floor(diff_ms / 60000);
diff_ms -= (minutes * 60000);
var seconds = Math.floor(diff_ms / 1000);
return zeroPad(hours, 2) + ':' + zeroPad(minutes, 2) + ':' + zeroPad(seconds, 2);
}
I have a date field in mysql that has datetime in the below period :
2014-05-31 15:00:55
I want to convert this value to "passed time" till current time.
for example if two hours are passed till the saved time,then I want something like this :
two hours ago
if three days are passed till the saved time,then it should be:
three days ago
I am trying to display the output with php as following :
<?php
echo '<p align="right">';
echo $row2['date'] ;
echo '</p>';
?>
I am new in PHP,Can anyone help me out.
You could try something like this:
function timeDiff(current, previous) {
var msPerMin = 60 * 1000;
var msPerHr = msPerMin * 60;
var msPerDay = msPerHr * 24;
var msPerMonth = msPerDay * 30;
var msPerYear = msPerDay * 365;
var elapsed = current - previous;
if (elapsed < msPerMin) {
return Math.round(elapsed / 1000) + ' seconds ago';
}
else if (elapsed < msPerHr) {
return Math.round(elapsed / msPerMin) + ' minutes ago';
}
else if (elapsed < msPerDay ) {
return Math.round(elapsed / msPerHr ) + ' hours ago';
}
else if (elapsed < msPerMonth) {
return 'approximately ' + Math.round(elapsed / msPerDay) + ' days ago';
}
else if (elapsed < msPerYear) {
return 'approximately ' + Math.round(elapsed / msPerMonth) + ' months ago';
}
else {
return 'approximately ' + Math.round(elapsed / msPerYear ) + ' years ago';
}
}
Source: Javascript timestamp to relative time (eg 2 seconds ago, one week ago etc), best methods?
This is how you implement it:
var now = new Date();
var someDate = new Date(2011, 04, 24, 12, 30, 00, 00);
alert(timeDiff(now, someDate));
Fiddle.
I'm looking for a way to show a timeago like output based on a iso timestamp from the db like: 2008-07-17T09:24:17Z
Output should be like:
Used today
Used on Tuesday
Used last Tuesday
Used more than a month ago
Something simple and more static that what you get with the jQuery timeago plugin: http://timeago.yarp.com/
Any suggestions? Thanks
You can turn the timestamp into a date object and compare it to a local (or some other) date object. Then classify the response based on the difference:
// Expects ISO8601 long format, no decimals of seconds
function localDateFromUTC(s) {
var x = s.split(/[-\s:tz]/i);
var d = Date.UTC(x[0], x[1], x[2], x[3], x[4], x[5], 0);
return new Date(d);
}
function aboutTime(s) {
var r = Math.round;
var now = new Date();
var then = localDateFromUTC(s);
var diff = r((now - then)/1000); // Convert to seconds
if (diff < 10) return 'a few seconds ago';
if (diff < 50) return 'less than a minute ago';
if (diff < 70) return 'about a minute ago';
if (diff < 35000) return 'about ' + r(diff/60) + ' minutes ago';
if (diff < 8.64e4) return 'about ' + r(diff/3600) + ' hours ago';
if (diff < 6.048e5) return 'about ' + r(diff/8.64e4) + ' days ago';
// and so on
return 'about ' + r(diff/6.048e5) + ' weeks ago';
}
alert(aboutTime('2008-07-17T09:24:17Z')); // about 200 weeks ago
You can get more clever regarding how the number is converted to an "about" string (e.g. an object with properties related to the "about" times, then convert the number to a property name).