Converting "2011-06-23T13:20:12+0000" to time ago - javascript

What is the "best" (and fastest) way to convert the date 2011-06-23T13:20:12+0000 into the following formats?
45 minutes ago
4 hours ago
2 days ago
5 weeks ago

Take a look at jQuery.timeago, might be what you're looking for.

John Resig to the rescue

I think that this will be fast enough:
function daysAgo(dt) {
var diff = Math.floor((new Date() - dt) / 86400000);
if (diff === 1)
{
return diff + ' day ago';
} else {
return diff + ' days ago';
}
}
function minsAgo(dt) {
var diff = Math.floor((new Date() - dt) / 60000);
if (diff === 1)
{
return diff + ' minute ago';
} else {
return diff + ' minutes ago';
}
}
var then = new Date('2011-06-23T13:20:12+0000');
document.write(then + '<br />');
document.write(daysAgo(then) + '<br />');
document.write(minsAgo(then));
You can write the other functions for weeks and hours similarly. Also, these are approximations because of the Math.floor call, but I figured that would be good enough.

Related

Converting datetime to "passed time" till current time

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.

Convert ISO time to H:MM am|pm in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript seconds to time with format hh:mm:ss
Seems to me that this is a simple task, but I have not yet managed to make this work.
Essentially, I am starting with a string that contains an ISO-formatted time (HH:MM:SS) and I am wondering how to convert it to H:MM am|pm using JavaScript.
Any help is much appreciated.
hello this may help you... its a jquery plugin called moments...
A lightweight (4.8k) javascript date library for parsing, manipulating, and formatting dates.
Moment.js
This simple function should do the trick:
function convertTime (isoTime) {
var hours = parseInt(isoTime.substring(0, 2), 10),
minutes = isoTime.substring(3, 5),
ampm = 'am';
if (hours == 12) {
ampm = 'pm';
} else if (hours == 0) {
hours = 12;
} else if (hours > 12) {
hours -= 12;
ampm = 'pm';
}
return hours + ':' + minutes + ' ' + ampm;
}
Should be self-explanatory. See this jsfiddle for example: http://jsfiddle.net/nscXP/3/
Just because there are solutions coming in that will fail to handle the noon hour or midnight hour properly, I'm going to toss my hat in the ring, even though it's not that different from what's been offered (aside than the fact it works properly):
var isoToCommonTime = function(iso) {
var groups = iso.match(/^(\d\d):(\d\d)/),
hour = +groups[1],
ampm = (hour >= 12) ? "pm" : "am";
if(hour > 12) {
hour -= 12;
} else if(hour === 0) {
hour = 12;
}
return hour + ":" + groups[2] + " " + ampm;
};
Something like this would work...
input = "12:34:45";
groups = input.match(/(.+):(.+):(.+)/);
if (groups[1] > 12) {
hour = groups[1] - 12;
unit = "pm";
} else {
hour = groups[1];
unit = "am";
}
minutes = groups[2];
Edit: There's some great points in the comments about issues with this at noon and midnight. I'll leave fixing these problems as an exercise to the reader. (I feel that the actual interesting part here is doing the string parsing)

Time display issue showing --2560 seconds ago when app runs in US

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.

Datejs getting the difference between dates

So here is my goal, I want to get how long ago a certain date was as a pretty readable string. Something like: '4 day and 3 hours ago'. I am using datejs and have both my dates currently as epochs.
I know I could subtract one epoch from the other, take the difference and then manually calculate the string to output. But this feels like something datejs would handle. However I see no documentation (of any js lib for that matter) expressing a means of converting a date object, or an epoch to a quantity of time.
any ideas, on how this best should be handled?
UPDATE
Let me be more clear. When I say human readable that means
1 day ago is 'yesterday'
2 days ago is '2 days ago'
30 seconds ago is 'just now'
1 year and 3 days and 12 seconds ago is '1 year ago'
What I ended up doing
prettyAgo = (ago) ->
ago = ago.getTime() if typeof ago is 'object'
diff = ((new Date()).getTime() - ago) / 1000
dayDiff = Math.floor(diff / 86400)
return false if isNaN(dayDiff) or dayDiff < 0
writer = ''
if dayDiff is 0
if diff < 1 then writer = 'just now'
else if diff < 60 then writer = Math.floor(diff)+' seconds ago'
else if diff < 120 then writer = '1 minute ago'
else if diff < 3600 then writer = Math.floor(diff / 60)+' minutes ago'
else if diff < 7200 then writer = '1 hour ago'
else if diff < 86400 then writer = Math.floor(diff / 3600)+' hours ago'
else if dayDiff is 1 then writer = 'yesterday'
else if dayDiff < 7 then writer = dayDiff+' days ago'
else if dayDiff is 7 then writer = '1 week ago'
else if dayDiff < 31 then writer = Math.ceil( dayDiff / 7 )+' weeks ago'
else writer = new Date(ago).toString 'MMM yyyy'
return writer
DateJS does handle this by including a class called TimeSpan (defined in time.js, not in the base JS file) which does the calculations for you. It doesn't do the formatting, so you'd need something like this:
function showDiff(date1, date2) {
var diff, rv, yrs;
diff = new TimeSpan(date2 - date1);
if (diff.days > 0) {
// A day or more difference
if (diff.days === 1) {
rv = "yesterday";
}
else if (diff.days >= 365) {
yrs = diff.days / 365;
if (yrs === 1) {
rv = "1 year ago";
}
else {
rv = yrs + " years ago";
}
}
else {
rv = diff.days + " ago";
}
}
else {
// Less than 1 day difference
if (diff.hours > 0) {
if (diff.hours === 1) {
rv = "1 hour ago";
}
else {
rv = diff.hours + " hours ago";
}
}
else if (diff.minutes > 0) {
if (diff.minutes === 1) {
rv = "1 minute ago";
}
else {
rv = diff.minutes + " minutes ago";
}
}
else {
rv = "just now";
}
return rv;
}
Obviously this isn't perfect and doesn't handle leap years and all that, but it should give you the idea.
Actually you can do that in pure JavaScript.
function format(num) {
var date = new Date(num),
time = [];
with(time) {
push(date.getUTCDate() - 1);
push(date.getUTCHours());
push(date.getUTCMinutes());
push(date.getUTCSeconds());
}
if (time[0] > 29) {
time[0] = Math.floor(date / 86400000);
}
return time[0] + " day " + time[1] + " hours " + time[2] + " mintues " + time[3] + " seconds ago";
}
http://jsfiddle.net/DerekL/NqTnF/

Given a timestamp, how to show timeago by days/weeks/months

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).

Categories

Resources