2

I have a JSON feed that drupal spits out time in this format: 2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?

meijiOrO
  • 411
  • 4
  • 7
  • 14

6 Answers6

6

Take a look at the timeago jQuery plugin which can be used programtically like

var t = jQuery.timeago("2010-12-16T04:41:35Z"); 

or on HTML elements like

<time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
<script type="javascript">
  jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
  });
</script>
David Glenn
  • 24,412
  • 19
  • 74
  • 94
  • 1
    I've used this plugin, it works perfectly and it is very easy to use. You can change the wording used just by doing $.timeago.settings.minute = "a minute"; for example. – Maricel Jan 18 '11 at 16:28
2

I think something on this page will help you. There's a couple formatting jQuery plugins toward the bottom. Good luck!

Slick23
  • 5,827
  • 10
  • 41
  • 72
1

Here is a highly relevant Stack Overflow post: How can I convert string to datetime with format specification in JavaScript?

Community
  • 1
  • 1
Kyle Wild
  • 8,845
  • 2
  • 36
  • 36
0

You can use regexp object in JS to build your own regular expression, separate hours-minutes-secs from the original string and then do whatever you want.

Tip: actual_date - your original string time

Fran Verona
  • 5,438
  • 6
  • 46
  • 85
0

does the 04:41:35 part is correct? or do you need like to take into consideration time zones and stuff?

because basically this can work:

var str = "2010-12-16T04:41:35Z"
var arr = str.split("T")
arr[0] = arr[0].split("-")
arr[1] = (arr[1].replace(/Z/ig,"")).split(":")
var year = arr[0][0]
var month = parseInt(arr[0][1],10)-1
var day = arr[0][2]
var hours = arr[1][0]
var minutes = arr[1][1]
var seconds = arr[1][2]
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var now = (new Date())
var diffMS = now.getTime() - d.getTime()
//alert ("difference in milliseconds: " + diffMS)

var hoursago = diffMS/1000/60
var ANDminutes = (diffMS - Math.floor(hoursago) * 1000*60)/1000

alert (Math.floor(hoursago) + " hours and " + ANDminutes + " minutes ago")
alfred
  • 1,000
  • 9
  • 13
0
<shameless_plug>

Here's a library which give you a humanized time difference.

https://github.com/layam/js_humanized_time_span

The output is completely customizable, allowing you to set different output formats for various time bands; So you could have:

'10 seconds ago'

or

'3 days and 2 hours ago'

you can even set custom time units.

Additionally it's native JS and so doesn't rely on any framework.

</shameless_plug>
Will Tomlins
  • 1,436
  • 16
  • 12