I have a javascript function
function relativeTime(time) {
var period = new Date(time);
var delta = new Date() - period;
if (delta <= 10000) { // Less than 10 seconds ago
return 'Just now';
}
var units = null;
var conversions = {
millisecond: 1, // ms -> ms
second: 1000, // ms -> sec
minute: 60, // sec -> min
hour: 60, // min -> hour
day: 24, // hour -> day
month: 30, // day -> month (roughly)
year: 12 // month -> year
};
for (var key in conversions) {
if (delta < conversions[key]) {
break;
}
else {
units = key;
delta = delta / conversions[key];
}
}
// Pluralize if necessary:
delta = Math.floor(delta);
if (delta !== 1) { units += 's'; }
return [delta, units, "ago"].join(' ');
}
that give relative time difference like facebook comment.
How can i call this function in my view. I am using mvc3. i am getting time from database like,
<span>
@item.wallTimeStamp
</span>
instead of that i want to call javascript function,
i have a tag
<span>
//call javascript function that will display time difference in this tag
</span>
how can i do that?
First, give the span id(or something else for identification)
<span id="relativeTime">
</span>
Then, using javascript, first calculate that relative time value using your function. Then, using jQuery.text(), set that value inside span
<script>
$(document).ready(function() {
var wallTimeStamp = '@item.wallTimeStamp';
var relativeTimeValue = relativeTime(wallTimeStamp);
$('#relativeTime').text(relativeTimeValue);
});
</scipt>
Code modification may be needed for multiple spans of that kind
$(document).ready(function() {
//called when the document is ready
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With