【问题标题】:new Date() only show the year or month and yearnew Date() 只显示年份或月份和年份
【发布时间】:2018-04-11 18:46:42
【问题描述】:
$scope.articles = [
    {
    link: "http://google.com",
    source: "Google",
    title: "hello",
    "date": new Date(2008, 4, 15)
    },
];

<tbody>
    <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ">
        <td>{{article.source}}</td>
        <td><a href="{{article.link}}" target="_blank" rel="noopener noreferrer">{{article.title}}</a></td>
        <td class="date-table-td">{{article.date | date:'longDate'}}</td>
    </tr>
</tbody><!-- End table body -->

嗨,我现在有这个。所以日期显示为 2008 年 5 月 15 日。如何仅显示年份或仅显示年+月?

谢谢。

【问题讨论】:

标签: javascript angularjs json


【解决方案1】:

根据the documentation,您可以使用date.getFullYear()获取YYYY格式的年份,使用date.getMonth()获取月份。

一个例子:

let list = document.getElementById('test');
let date = new Date(2008, 4, 15);


// year
let yearNode = document.createElement("li");
yearNode.appendChild(document.createTextNode(date.getFullYear()));

list.appendChild(yearNode)

// year + month

let yearMonthNode = document.createElement("li");
yearMonthNode.appendChild(document.createTextNode(date.getFullYear() + " " + date.getMonth()))

list.appendChild(yearMonthNode)
<ul id="test">

</ul>

【讨论】:

  • 嗨,我试过 "date": new Date('2008, 4, 15').getFullYear() 但它返回 1969 年 12 月 31 日
  • 删除 ' 或在项目之间添加破折号。 new Date('2018-4-15').getFullYear() 可以正常工作。
  • 谢谢,我忘了提到我在主页上有这个{{article.date | date:'longDate'}}。当我删除 date:'longDate' 并添加 "date": new Date('2008, 4, 15').getFullYear() 时,它起作用了,所以这两个似乎是冲突的。但是,现在我已经删除了 longDate 格式,日期的格式不再正确。编辑了我原来的帖子。
【解决方案2】:

date.getMonth() 你需要为此 +1 var month = date.getMonth() + 1

【讨论】:

    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 2021-06-17
    • 2016-11-04
    • 2018-06-28
    • 2011-06-11
    • 2017-03-04
    相关资源
    最近更新 更多