每年获取最小和最大毫秒

时间:2018-07-12 14:35:16

标签: javascript momentjs

鉴于需要花费一年的javascript函数,如何获得该年份的最小和最大毫秒数。 (即,最小为1月1日(年)的00:00.000,最大为12月31日11:59:59.999)?

我是否需要创建一个表示这些值的字符串并解析它们,还是有一个更简单的方法?

4 个答案:

答案 0 :(得分:2)

您可以使用1月1日上午12:00和12月31日下午11:59创建这样的函数。作为参考点:

function getMinMaxMilliseconds(year) {
    // Get seconds of January 1, 12:00 a.m. of that year.
    let minMilliseconds = new Date(year, 0, 1, 0, 0, 0, 0).getTime();
      
    // Get seconds of December 31, 11:59 p.m. of that year.
    let maxMilliseconds = new Date(year, 23, 31, 11, 59, 59, 999).getTime();

    // Return as an object (you could change this to whatever format you like).
    return { minMilliseconds, maxMilliseconds };
}


// Example:

console.log(getMinMaxMilliseconds(2018));

答案 1 :(得分:2)

带有瞬间(使用endOf()valueOf()):

function getMinMillis(year){
  return moment({y: year}).valueOf();
}
function getMaxMillis(year){
  return moment({y: year}).endOf('year').valueOf();
}
console.log(getMinMillis(2018), getMaxMillis(2018));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

使用本机JavaScript日期:

function getMinMillis(year){
  return new Date(year, 0, 1, 0, 0, 0, 0).valueOf();
}
function getMaxMillis(year){
  return new Date(year, 11, 31, 23, 59, 59, 999).valueOf();
}
console.log(getMinMillis(2018), getMaxMillis(2018));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

答案 2 :(得分:1)

Moment具有startOf()和endOf()方法,可以按以下方式使用它们来获取给定年份的开始和结束的毫秒数。

function getMillisecondRangeForYear(year) {

    var date = moment({y: year});

    return {
        "min": date.startOf("year").valueOf(),
        "max": date.endOf("year").valueOf()
    };
}

答案 3 :(得分:0)

您可以按照https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date所述创建日期对象。 例如:

   new Date(yearInput, 1 [, 1 [, 0 [, 0 [, 0 [, 0]]]]]);

将为最小值创建一个日期对象。