jQuery 使用 Moment.js 获取当年的第一天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21834970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:42:41  来源:igfitidea点击:

Get the first day of the current year using Moment.js

jquerytypescriptmomentjs

提问by user3214545

I have two input fields to search between dates. I want the start date to default to the first day of the current year and the end date to default to today. I have the end date but I am unsure of how to get it to display the start.

我有两个输入字段可以在日期之间进行搜索。我希望开始日期默认为当年的第一天,结束日期默认为今天。我有结束日期,但我不确定如何让它显示开始日期。

var defaultStart =
var defaultEnd = moment((new Date()).valueOf());
$('#searchStart').val(defaultStart.format('DD/MM/YYYY'));
$('#searchEnd').val(defaultEnd.format('DD/MM/YYYY'));

采纳答案by Tim S. Van Haren

var thisYear = (new Date()).getFullYear();    
var start = new Date("1/1/" + thisYear);
var defaultStart = moment(start.valueOf());

回答by m007

You could do this:

你可以这样做:

moment().startOf('year');

formatby doing something like this:

通过执行以下操作来格式化

moment().startOf('year').format('MM/DD/YYYY');

回答by E.J. Brennan

var defaultStart = '01/01/'+new Date().getFullYear()

回答by Koga

To get the start date and end date of any given year. You can pass a year as a parameter to moment.

获取任何给定年份的开始日期和结束日期。您可以将一年作为参数传递给 moment。

startDateOfTheYear = moment([year]; endDateOfTheYear = moment([year]).endOf('year');

startDateOfTheYear = moment([year]; endDateOfTheYear = moment([year]).endOf('year');