简体   繁体   English

Javascript。 将datetime转换为漂亮的日期。 奇怪的格式

[英]Javascript. Convert datetime to pretty date. Strange format

How can I, using Javascript, convert the below data to pretty format, ie "2 days ago"? 如何使用Javascript将以下数据转换为漂亮的格式,即“ 2天前”?

2011-08-11 16:12:31.119218+0000 2011-08-11 16:12:31.119218 + 0000

What is this format called? 这种格式叫什么?

Thankful for all input! 感谢所有输入!

I think that format is called "fuzzy time". 我认为这种格式称为“模糊时间”。 Here's a good jquery library for that: http://timeago.yarp.com/ . 这是一个很好的jquery库: http : //timeago.yarp.com/ And here's one that doesn't require jquery, but will use it if it's available: http://ejohn.org/blog/javascript-pretty-date/ 这是一个不需要jquery的查询,但是如果可用,它将使用它: http : //ejohn.org/blog/javascript-pretty-date/

https://github.com/zachleat/Humane-Dates https://github.com/zachleat/Humane-Dates

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 *
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 *
 * Licensed under the MIT license.
 */

function humaneDate(date, compareTo){

    if(!date) {
        return;
    }

    var lang = {
            ago: 'Ago',
            from: '',
            now: 'Just Now',
            minute: 'Minute',
            minutes: 'Minutes',
            hour: 'Hour',
            hours: 'Hours',
            day: 'Day',
            days: 'Days',
            week: 'Week',
            weeks: 'Weeks',
            month: 'Month',
            months: 'Months',
            year: 'Year',
            years: 'Years'
        },
        formats = [
            [60, lang.now],
            [3600, lang.minute, lang.minutes, 60], // 60 minutes, 1 minute
            [86400, lang.hour, lang.hours, 3600], // 24 hours, 1 hour
            [604800, lang.day, lang.days, 86400], // 7 days, 1 day
            [2628000, lang.week, lang.weeks, 604800], // ~1 month, 1 week
            [31536000, lang.month, lang.months, 2628000], // 1 year, ~1 month
            [Infinity, lang.year, lang.years, 31536000] // Infinity, 1 year
        ],
        isString = typeof date == 'string',
        date = isString ?
                    new Date(('' + date).replace(/-/g,"/").replace(/[TZ]/g," ")) :
                    date,
        compareTo = compareTo || new Date,
        seconds = (compareTo - date +
                        (compareTo.getTimezoneOffset() -
                            // if we received a GMT time from a string, doesn't include time zone bias
                            // if we got a date object, the time zone is built in, we need to remove it.
                            (isString ? 0 : date.getTimezoneOffset())
                        ) * 60000
                    ) / 1000,
        token;

    if(seconds < 0) {
        seconds = Math.abs(seconds);
        token = lang.from ? ' ' + lang.from : '';
    } else {
        token = lang.ago ? ' ' + lang.ago : '';
    }

    /*
     * 0 seconds && < 60 seconds        Now
     * 60 seconds                       1 Minute
     * > 60 seconds && < 60 minutes     X Minutes
     * 60 minutes                       1 Hour
     * > 60 minutes && < 24 hours       X Hours
     * 24 hours                         1 Day
     * > 24 hours && < 7 days           X Days
     * 7 days                           1 Week
     * > 7 days && < ~ 1 Month          X Weeks
     * ~ 1 Month                        1 Month
     * > ~ 1 Month && < 1 Year          X Months
     * 1 Year                           1 Year
     * > 1 Year                         X Years
     *
     * Single units are +10%. 1 Year shows first at 1 Year + 10%
     */

    function normalize(val, single)
    {
        var margin = 0.1;
        if(val >= single && val <= single * (1+margin)) {
            return single;
        }
        return val;
    }

    for(var i = 0, format = formats[0]; formats[i]; format = formats[++i]) {
        if(seconds < format[0]) {
            if(i === 0) {
                // Now
                return format[1];
            }

            var val = Math.ceil(normalize(seconds, format[3]) / (format[3]));
            return val +
                    ' ' +
                    (val != 1 ? format[2] : format[1]) +
                    (i > 0 ? token : '');
        }
    }
};

if(typeof jQuery != 'undefined') {
    jQuery.fn.humaneDates = function(options)
    {
        var settings = jQuery.extend({
            'lowercase': false
        }, options);

        return this.each(function()
        {
            var $t = jQuery(this),
                date = $t.attr('datetime') || $t.attr('title');

            date = humaneDate(date);

            if(date && settings['lowercase']) {
                date = date.toLowerCase();
            }

            if(date && $t.html() != date) {
                // don't modify the dom if we don't have to
                $t.html(date);
            }
        });
    };
}

To produce "2 days ago" use Date.prototype.getTime() which returns the time in milliseconds since January 01, 1970 according to universal time. 要生成“ 2天前”,请使用Date.prototype.getTime() ,它根据通用时间返回自1970年1月1日以来的时间(以毫秒为单位)。

The following is an example on how to return a pretty date based on date differences for dates less than a week, otherwise, it returns Date.prototype.toDateString() : 以下是有关如何根据日期差返回少于一周的日期的漂亮日期的示例,否则,它将返回Date.prototype.toDateString()

function prettyDate(date, startDate) {
  var secs = Math.floor((date.getTime() - startDate.getTime()) / 1000);
  if (secs < 60) return secs + " sec(s) ago";
  if (secs < 3600) return Math.floor(secs / 60) + " min(s) ago";
  if (secs < 86400) return Math.floor(secs / 3600) + " hour(s) ago";
  if (secs < 604800) return Math.floor(secs / 86400) + " day(s) ago";
  return date.toDateString();
}

Take a look at javascripts date object http://www.w3schools.com/jsref/jsref_obj_date.asp . 看看javascripts日期对象http://www.w3schools.com/jsref/jsref_obj_date.asp You can set this into a date object and create another date object to compare to. 您可以将其设置为日期对象,并创建另一个要比较的日期对象。

对于这些类型的数据格式问题, Date.js非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM