星期五, 1月 11, 2013

[jQuery plugin] 秒 轉換 為時:分:秒格式

找到的秒數轉時分秒格式的範例
jQuery.fn.time_from_seconds = function() {
    return this.each(function() {
        var t = parseInt($(this).text(), 10);
        $(this).data('original', t);
        var h = Math.floor(t / 3600);
        t %= 3600;
        var m = Math.floor(t / 60);
        var s = Math.floor(t % 60);
        $(this).text((h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') +
                     (m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') +
                     s + ' second' + ((s > 1) ? 's' : ''));
    });
};
加強一下可以支援多國語言
/**
 * Time from seconds
 * Refer from 
 * @author ken tsai
 * @date 2013/1/13
 **/
;(function($) {
 
 $.fn.time_from_seconds = function() {
     return this.each(function() {
         var t = parseInt($(this).text(), 10);
         $(this).data('original', t);
         $(this).text($.timeFromSeconds(t));
     });
 };
 
 $.timeFromSeconds = function(t){
  
    var h = Math.floor(t / 3600);
       t %= 3600;
       var m = Math.floor(t / 60);
       var s = Math.floor(t % 60);
       
//       var conv = (h > 0 ? h + ' hour' + ((h > 1) ? 's ' : ' ') : '') +
//       (m > 0 ? m + ' minute' + ((m > 1) ? 's ' : ' ') : '') +
//       s + ' second' + ((s > 1) ? 's' : '');
       var hour = "", minute = "", second = "";
       if($.timeFromSeconds.defaults.plural){
        hour = (h > 0 ? h + " " + $.timeFromSeconds.defaults.hours + ((h > 1) ? "s " : " ") : " ");
        minute =  (m > 0 ? m + " " + $.timeFromSeconds.defaults.minutes + ((m > 1) ? "s " : " "):" ");
        second =  (s > 0 ? s + " " + $.timeFromSeconds.defaults.seconds + ((s > 1) ? "s " : " "): " ");
       }else{
        hour = (h > 0 ? h + " " + $.timeFromSeconds.defaults.hours: " ");
        minute =  (m > 0 ? m + " " + $.timeFromSeconds.defaults.minutes: " ");
        second =  (s > 0 ? s + " " + $.timeFromSeconds.defaults.seconds: " ");
       }
       return hour + minute + second;
 };

 $.timeFromSeconds.setDefaults = function(defaults){
  $.timeFromSeconds.defaults = defaults;
 };
 
 $.timeFromSeconds.defaults = {
  hours:"hour",
  minutes:"minute",
  seconds:"second",
  plural:true
 };
 
 
})(jQuery);

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails