将 AngularJS 中的时间戳格式化为自定义要求

Format timestamp in AngularJS to a custom requirement

本文关键字:自定义 格式化 时间戳 AngularJS      更新时间:2023-09-26

我有一串从新帖子返回的数字,该数字在提交时以new Date().getTime()格式加盖时间戳。我希望放置一个持续时间时间戳,例如(new Date().getTime() of submitted post - current date time)或基本上是从提交帖子开始经过的日期时间。

如果一个月的持续时间<减法将返回分钟>几小时几天前(但一个月的定义各不相同,有些二月有 28 天?不确定是否有全局时区调整。如果>一个月,则将其显示为month (Jan, Mar, Dec etc)year 2014,例如不涉及任何持续时间。

我听说过 moment.JS但不确定上面是否有这样的定制。我应该如何处理转换?如果有示例代码可供参考,请不胜感激。

非常感谢!

我有一串从新 Date((.getTime(( 返回的数字

这将是一个数字,表示自 1970-01-01T00:00:00Z(ECMAScript 纪元(以来的毫秒数和执行代码的 UTC 时间。

并保存在后端。我希望放置一个持续时间时间戳,例如(new Date((.getTime(( - now(((。

如果 now()Date.now() 的简写,则该表达式的结果将为零 (0(,因为两个表达式将表示同一时刻。

但是我希望过滤器将其显示为分钟,几小时,几天前

将以毫秒为单位的值转换为天、小时、分钟、秒的值是微不足道的。

如果它少于一个月(但一个月的定义各不相同,二月有时有 28 天?我不确定时间戳字符串是否考虑了全局时区调整。

Date 对象中心的时间值是自纪元以来的 UTC 毫秒。Date 对象还具有由系统设置确定的偏移量,用于计算本地时间值。有 UTC 方法获取 UTC 值和非 UTC 方法获取本地值。

如果超过一个月,则将其显示为月份(1月,3月,12月等(和2014年,例如不涉及任何持续时间。

减去两个时间值的结果是一个标量数字,它没有月或年的概念,它只是表示一个持续时间,而不是一个时刻。因此,只有在存在特定的起点(纪元(和方向时,将数字转换为"月"才有意义。

例如

1月1日+31天->2月1日所以一个月,但6月1日+31天->7月2日所以1个月零1天。

1月1日 - 31天 -> 12月1日,一个月,6月1日 -

31天 -> 5月1日,

1个月。

我听说过时刻JS,但不确定是否有这样的持续时间自定义

我对时刻.js了解不多,只知道我从来没有发现需要它。

我应该如何处理转换?

首先阐明您的要求。也许您想将持续时间表示为从特定时间点(例如现在或 2014 年 6 月 1 日或其他时间点(开始的月、天、小时等?

以上有些是

微不足道的,有些是相当困难的,取决于行政规则,例如 2012 年 2 月 29 日 + 1 年 2013 年 2 月 28 日还是 2013 年 3 月 1 日?

编辑

下面的示例代码是确定两个日期之间的年、月和日的一种相当可靠的方法。它还执行时差小于 1 天(即 8.64e7 千毫秒(的小时:分钟:秒。

它可能看起来像很多代码,大部分是在做年,月,天部分。

/**
 * Return the number of days in the month for the given year.
 * Month is calendar month (Jan=1, Feb=2, etc.).
 * @param {number} [month]
 * @param {number} [year]
 * @returns {number}
 * Default is current month, current year
*/
function getDaysInMonth(month, year) {
  var d = new Date();
  d.setHours(12,0,0,0);
  if (typeof month == 'undefined') month = d.getMonth() + 1;
  if (typeof year  == 'undefined') year  = d.getFullYear();
  d.setFullYear(year, month, 0);
  return d.getDate();
}
/**
 * Add years to a given Date, modifies the Date.
 * If adding years to 29 Feb rolls over to March 1,
 * then the date is set to 28 Feb.
 * @param {Date} date - Date to add years to
 * @param {number} years - Number of years to add
 * @returns {Date} Modified original date object
*/
function addYears(date, years) {
  var m = date.getMonth();
  date.setFullYear(date.getFullYear() + years);
  // Deal with leap year: if 29 Feb -> 1 Mar set back to 28 Feb
  if (date.getMonth() != m) {
    date.setDate(0);
  }
  return date;
}
/**
 * Add months to a given Date, modifies the Date.
 * If adding months causes the date to roll over an extra month,
 * the date is set to last day of previous month.
 *
 * e.g. 31 May + 1 month -> 30 June, not 1 July
 *      31 Jan + 1 month -> 28 Feb or 29 Feb if leap year
 * @param {Date} date - Date to add months to
 * @param {number} months - Number of months to add
 * @returns {Date} Modified original
*/
function addMonths(date, months) {
    var n = date.getDate();
    date.setMonth(date.getMonth() + months);
    if (date.getDate() != n) {
        date.setDate(0);
    }
    return date;
}
/**
 * Add days to a given Date, modifies the Date.
 * @param {Date} date - Date to add days to
 * @param {number} days - Number of days to add
 * @returns {Date} Modified original
*/
function addDays(date, days) {
    date.setDate(date.getDate() + days);
    return date;
}
/**
 * Convert seconds to hh:mm:ss
 * @param {number|string} secs
 * @returns {number}
*/
function secondsToHMS(secs) {
  function z(n){return (n<10?'0':'') + n;}
  var sign = secs < 0? '-':'';
  secs = Math.abs(secs);
  return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
/**
 * Get the time between two dates as years, months and days.
 * For startDate of 29 Feb, whole year is 28 Feb in following year or
 * 29 Feb if endDate is a leap year. Some systems use 1 Mar.
 * @param {Date} startDate
 * @param {Date} [endDate]
 * @returns {string} 'y years, m moths and d days'
 * If endDate not provided, current date is used.
 * endDate must be after startDate.
*/
function getAge(startDate, endDate) {
    // Return undefined if start date is after end date
    if (startDate > endDate) return;
    var d, d0, d1, years, months, days;
    var startMonth = startDate.getMonth();
    d1 = endDate? new Date(+endDate) : new Date();
    d1.setHours(0,0,0,0);
    d = new Date(+startDate);
    d.setHours(0,0,0,0);
    d0 = new Date(+d);
    years = d1.getFullYear() - d.getFullYear();
    addYears(d, years);
    if (d > d1) {
        --years;
        d = new Date(+d0);
        addYears(d, years);
    }
    months = d1.getMonth() - d.getMonth();
    // Deal with -ve month difference
    if (months < 0) {
        months += 12;
    // Deal with months the same and difference < 1 year
    } else if (months == 0 && d.getFullYear() != d1.getFullYear()) {
        months = 11;
    }
    addMonths(d, months);
    if (d > d1) {
        --months;
        d = new Date(+d0);
        addYears(d, years);
        addMonths(d, months);
    }
    days = d1.getDate() - d.getDate();
    if (days < 0 ) {
        days += getDaysInMonth(d.getMonth()+1, d.getFullYear());
    } else if (days == 0 && d1.getMonth() != d.getMonth()) {
        days = getDaysInMonth(d.getMonth()+1, d.getFullYear()) - 1;
    }
    // Helper to make words plural if num != 1
    function s(num, word) {return word + (num == 1? '' : 's')}
    return years  + s(years,  ' year' ) + ', ' +
           months + s(months, ' month') + ', ' +
           days   + s(days,   ' day'  );
}

// Basic function to parse an ISO 8601 format string as a
// local time. Any timezone is ignored.
// Honours 2 digit years, so 14 is not 1914.
function parseString(s) {
  var d = new Date();
  b = s.split(/'D+/);
  d.setFullYear(b[0], b[1] - 1, b[2]);
  d.setHours(b[3] || 0, b[4] || 0, b[5]);
  return d;
}

function showDuration() {
  var el = document.getElementById('d0');
  var now = new Date();
  // Convert date string to a Date object
  var then = parseString(document.getElementById('i0').value);
  // If not a valid date, do nothing
  if (!then) return;
  // If difference greater than 1 day, show years, months, etc.
  // Otherwise, show h:m:s
  el.innerHTML = ((now - then) > 8.64e7? getAge(then, now) :
                  secondsToHMS(Math.abs(then - now)/1000 | 0)) + ' ago.';
}

一些标记:

<input id="i0" value="2014-06-23T20:28:09">
<button onclick="showDuration()">Show duration</button>
<br>
<div id="d0"></div>

是的,你可以使用moment.js,它处理所有这些。 您可以从现在开始使用:

moment([2007, 0, 29]).fromNow(); // 4 years ago

如果您不喜欢它为您提供的内容,则可以自定义:

moment.relativeTimeThreshold('d');  // 26

另请参阅日历,它是可自定义的。

或者,您可以使用差异

a.diff(b, 'days'(//1

最后,您还可以使用持续时间

moment.duration(2, 'weeks');

要格式化其显示方式,您可以使用格式

moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"

它还支持时区和UTC以及本地化。