1

I have this function:

function get_time_zone_offset() {   
    var current_date = new Date();   
    return -current_date.getTimezoneOffset() / 60; 
}

I want a jQuery code to change every span which class is 'timeago' title value to its value plus the number the function above returns. For example:

Before:

<span class="timeago" title="7/4/2012 9:28:30 AM">7/4/2012 9:28:30 AM</span>

After:

<span class="timeago" title="7/4/2012 12:28:30 PM">7/4/2012 12:28:30 PM</span>
Salman A
  • 262,204
  • 82
  • 430
  • 521
Rashad Ahmad
  • 71
  • 1
  • 1
  • 6

3 Answers3

2

Assuming 7/4/2012 9:28:30 AM represents UTC, you can let the Date object do all the math:

function formatDate(d) {
    var yy = d.getFullYear();
    var mm = d.getMonth() + 1;
    var dd = d.getDate();
    var hh = d.getHours();
    var ii = d.getMinutes();
    var ss = d.getSeconds();
    var ap;
    if (hh < 12) {
        if (hh === 0) {
            hh = 12;
        }
        ap = "AM";
    }
    else {
        if (hh > 12) {
            hh -= 12;
        }
        ap = "PM";
    }
    return mm + "/" + dd + "/" + yy + " " + hh + ":" + ii + ":" + ss + " " + ap;
}
$("span.timeago").each(function() {
    var dateInput = $(this).text();
    var dateInUTC = new Date(dateInput + " +0000"); // note: +0000 is the key
    var dateOutput = formatDate(dateInUTC);
    $(this).attr("title", dateOutput).text(dateOutput);
});

This assumes that the date is parsable. Here is a demo.

Salman A
  • 262,204
  • 82
  • 430
  • 521
0

It's pretty straightforward by passing a function to .attr [docs]:

var offset = get_time_zone_offset();
$('span.timeago').attr('title', function(i, val) {
    return +val + offset;
});

If you have to convert the value to a proper timestamp first, have a look at How to convert from date to unix_timestamp using javascript.

If you are using the Timeago plugin, note this remark:

Are you concerned about time zone support? Don't be. Timeago handles this too. As long as your timestamps are in ISO 8601 format and include a full time zone designator (±hhmm), everything should work out of the box regardless of the time zone that your visitors live in.

So you might not even have to do this conversion manually. Just add the proper timezone information to values.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

It seems a simple loop like this should work:

$('span.timeago').each(function(index, elm) {
    var newVal = $(elm).attr('title') * 1 + get_time_zone_offset(); // multiply by 1 to suppress string concatenation
    $(elm).attr('title', newVal);
});