2011-05-24 6 views
31

मैं एक अच्छा जेएस स्निपेट ढूंढ रहा हूं ताकि एक टाइमस्टैम्प (उदा। ट्विटर एपीआई से) को एक अच्छे उपयोगकर्ता के अनुकूल रिश्तेदार समय (जैसे 2 सेकंड पहले, एक सप्ताह पहले इत्यादि) में परिवर्तित किया जा सके।रिश्तेदार समय के लिए जावास्क्रिप्ट टाइमस्टैम्प (उदाहरण के लिए 2 सेकंड पहले, एक सप्ताह पहले आदि), सर्वोत्तम तरीकों?

कोई भी अपनी पसंदीदा विधियों को साझा करने की देखभाल करता है (अधिमानतः प्लगइन का उपयोग नहीं कर रहा है)?

उत्तर

62

वैसे यह बहुत आसान है यदि आप सटीकता से अत्यधिक चिंतित नहीं हैं। तुच्छ विधि के साथ क्या गलत है?

function timeDifference(current, previous) { 

    var msPerMinute = 60 * 1000; 
    var msPerHour = msPerMinute * 60; 
    var msPerDay = msPerHour * 24; 
    var msPerMonth = msPerDay * 30; 
    var msPerYear = msPerDay * 365; 

    var elapsed = current - previous; 

    if (elapsed < msPerMinute) { 
     return Math.round(elapsed/1000) + ' seconds ago'; 
    } 

    else if (elapsed < msPerHour) { 
     return Math.round(elapsed/msPerMinute) + ' minutes ago'; 
    } 

    else if (elapsed < msPerDay) { 
     return Math.round(elapsed/msPerHour) + ' 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'; 
    } 
} 

उदाहरण here कार्य करना।

आप इसे एकवचन मूल्यों को बेहतर तरीके से संभालने के लिए ट्विक करना चाहते हैं (उदाहरण के लिए 1 day1 days के बजाय) यदि यह आपको परेशान करता है।

+0

ब्रिल! मुझे इसकी ही खोज थी! मैं बुनियादी सिद्धांत जानता था लेकिन यह सुनिश्चित करना चाहता था कि यह निश्चित रूप से करने का सबसे अच्छा तरीका क्या है :) – wilsonpage

5

तादा! टाइमगो: http://timeago.yarp.com/

ओह लटका - बिना प्लगइन के? तब वह क्यों है? मुझे लगता है कि आप प्लगइन फ़ाइल खोल सकते हैं और इससे बाहर निकल सकते हैं।

+0

अच्छा, वास्तव में यह एक प्लगइन है। ओपी एक का उपयोग किये बिना समाधान के लिए पूछता है। – pimvdb

+0

बस कोड को यथासंभव स्वच्छ और पूरी तरह से अनुकूलन रखना चाहते हैं। मुझे नहीं लगता कि यह एक बड़ा मजा है। इसलिए 10-15 लाइनों को एक प्लगइन की अन्य बंडल कार्यक्षमता की आवश्यकता नहीं है। – wilsonpage

+1

ठीक है, स्रोत कोड काफी छोटा है और ऐसा लगता है कि जब तक आप एमआईटी लाइसेंस हेडर रखते हैं, तब तक आपकी आवश्यकताओं के लिए इसे निकाला जा सकता है। http://timeago.yarp.com/jquery.timeago.js –

13

हैं प्लगइन के बिना चहचहाना समय पहले की सटीक नकल है:

function timeSince(timeStamp) { 
    var now = new Date(), 
     secondsPast = (now.getTime() - timeStamp.getTime())/1000; 
    if(secondsPast < 60){ 
     return parseInt(secondsPast) + 's'; 
    } 
    if(secondsPast < 3600){ 
     return parseInt(secondsPast/60) + 'm'; 
    } 
    if(secondsPast <= 86400){ 
     return parseInt(secondsPast/3600) + 'h'; 
    } 
    if(secondsPast > 86400){ 
     day = timeStamp.getDate(); 
     month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ",""); 
     year = timeStamp.getFullYear() == now.getFullYear() ? "" : " "+timeStamp.getFullYear(); 
     return day + " " + month + year; 
    } 
    } 

सार https://gist.github.com/timuric/11386129

फिडल http://jsfiddle.net/qE8Lu/1/

आशा है कि यह मदद करता है।

+0

आप, महोदय, चीजें जानते हैं! बहुत बहुत धन्यवाद। एक तृतीय पक्ष पुस्तकालय का उपयोग क्यों करें? – zanona

1

किसी भी दिलचस्पी के लिए, मैंने ऐसा करने के लिए हैंडलबार सहायक बनाने का अंत किया। उपयोग:

{{#beautify_date}} 
     {{timestamp_ms}} 
    {{/beautify_date}} 

हेल्पर:

Handlebars.registerHelper('beautify_date', function(options) { 
     var timeAgo = new Date(parseInt(options.fn(this))); 

     if (Object.prototype.toString.call(timeAgo) === "[object Date]") { 
      if (isNaN(timeAgo.getTime())) { 
       return 'Not Valid'; 
      } else { 
       var seconds = Math.floor((new Date() - timeAgo)/1000), 
       intervals = [ 
        Math.floor(seconds/31536000), 
        Math.floor(seconds/2592000), 
        Math.floor(seconds/86400), 
        Math.floor(seconds/3600), 
        Math.floor(seconds/60) 
       ], 
       times = [ 
        'year', 
        'month', 
        'day', 
        'hour', 
        'minute' 
       ]; 

       var key; 
       for(key in intervals) { 
        if (intervals[key] > 1) 
         return intervals[key] + ' ' + times[key] + 's ago'; 
        else if (intervals[key] === 1) 
         return intervals[key] + ' ' + times[key] + ' ago'; 
       } 

       return Math.floor(seconds) + ' seconds ago'; 
      } 
     } else { 
      return 'Not Valid'; 
     } 
    }); 
2

inspirated Diego Castillo awnser's पर और timeago.js प्लगइन में, मैं इस के लिए अपने खुद के वेनिला प्लगइन लिखा था।

var timeElement = document.querySelector('time'), 
    time = new Date(timeElement.getAttribute('datetime')); 

timeElement.innerText = TimeAgo.inWords(time.getTime()); 

var TimeAgo = (function() { 
 
    var self = {}; 
 
    
 
    // Public Methods 
 
    self.locales = { 
 
    prefix: '', 
 
    sufix: 'ago', 
 
    
 
    seconds: 'less than a minute', 
 
    minute: 'about a minute', 
 
    minutes: '%d minutes', 
 
    hour: 'about an hour', 
 
    hours: 'about %d hours', 
 
    day:  'a day', 
 
    days: '%d days', 
 
    month: 'about a month', 
 
    months: '%d months', 
 
    year: 'about a year', 
 
    years: '%d years' 
 
    }; 
 
    
 
    self.inWords = function(timeAgo) { 
 
    var seconds = Math.floor((new Date() - parseInt(timeAgo))/1000), 
 
     separator = this.locales.separator || ' ', 
 
     words = this.locales.prefix + separator, 
 
     interval = 0, 
 
     intervals = { 
 
      year: seconds/31536000, 
 
      month: seconds/2592000, 
 
      day: seconds/86400, 
 
      hour: seconds/3600, 
 
      minute: seconds/60 
 
     }; 
 
    
 
    var distance = this.locales.seconds; 
 
    
 
    for (var key in intervals) { 
 
     interval = Math.floor(intervals[key]); 
 
     
 
     if (interval > 1) { 
 
     distance = this.locales[key + 's']; 
 
     break; 
 
     } else if (interval === 1) { 
 
     distance = this.locales[key]; 
 
     break; 
 
     } 
 
    } 
 
    
 
    distance = distance.replace(/%d/i, interval); 
 
    words += distance + separator + this.locales.sufix; 
 

 
    return words.trim(); 
 
    }; 
 
    
 
    return self; 
 
}()); 
 

 

 
// USAGE 
 
var timeElement = document.querySelector('time'), 
 
    time = new Date(timeElement.getAttribute('datetime')); 
 

 
timeElement.innerText = TimeAgo.inWords(time.getTime());
<time datetime="2016-06-13"></time>

3

Datetime प्लगइन्स मौजूद हैं, क्योंकि यह यह सही पाने के लिए बहुत मुश्किल है। यह video explaining date-time inconsistencies इस मुद्दे पर कुछ प्रकाश डालेगा।

प्लगइन के बिना सभी उपरोक्त समाधान गलत हैं।

प्लगइन का उपयोग करने के लिए दिनांक और समय के साथ काम करने के लिए बेहतर है। इसके साथ सौदा करने वाले सैकड़ों प्लगइन में से, हम Moment.js का उपयोग करते हैं और यह नौकरी कर रहा है।

twitter API dcumentation से हम उनका टाइमस्टैम्प प्रारूप देख सकते हैं:

"created_at":"Wed Aug 27 13:08:45 +0000 2008" 

हम Moment.js

const postDatetime = moment(
    "Wed Aug 27 13:08:45 +0000 2008", 
    "dddd, MMMM Do, h:mm:ss a, YYYY" 
); 
const now = moment(); 
const timeAgo = now.diff(postDatetime, 'seconds'); 

साथ इसके साथ पार्स diff के लिए पसंदीदा समय इकाई निर्दिष्ट करने के लिए कर सकते हैं, हम isSame उपयोग कर सकते हैं तरीका। उदाहरण के लिए:

if (now.isSame(postDatetime, 'day')) { 
    const timeUnit = 'days'; 
} 

कुल मिलाकर, कुछ के निर्माण की तरह: गणना: ("कैसे बहुत पहले?" यानी)

`Posted ${timeAgo} ${timeUnit} ago`; 

सापेक्ष समय से निपटने के लिए अपने प्लगइन के दस्तावेज़ देखें।

1

इस उद्देश्य के लिए sugar.js और relative फ़ंक्शन भी है।

सापेक्ष - वर्तमान दिनांक ("पहले" या "अब से") के सापेक्ष इकाइयों में एक स्ट्रिंग आउटपुट करता है।

0

आप इस उद्देश्य के लिए मशीनपैक-डेटाटाइम का उपयोग कर सकते हैं। यह परिभाषित एपीआई के साथ आसान और स्पष्ट है।

tutorialSchema.virtual('createdOn').get(function() { 
    const DateTime = require('machinepack-datetime'); 
    let timeAgoString = ""; 
    try { 
     timeAgoString = DateTime.timeFrom({ 
      toWhen: DateTime.parse({ 
       datetime: this.createdAt 
      }).execSync(), 
      fromWhen: new Date().getTime() 
     }).execSync(); 
    } catch(err) { 
     console.log('error getting createdon', err); 
    } 
    return timeAgoString; // a second ago 
}); 
0

यदि आपको बहुभाषी की आवश्यकता है और पल जैसी बड़ी लाइब्रेरी नहीं जोड़ना है। याहू से intl-relativeformat यह एक अच्छा समाधान है।

var rf = new IntlRelativeFormat('en-US'); 

var posts = [ 
    { 
     id : 1, 
     title: 'Some Blog Post', 
     date : new Date(1426271670524) 
    }, 
    { 
     id : 2, 
     title: 'Another Blog Post', 
     date : new Date(1426278870524) 
    } 
]; 

posts.forEach(function (post) { 
    console.log(rf.format(post.date)); 
}); 
// => "3 hours ago" 
// => "1 hour ago" 
संबंधित मुद्दे