Given a javascript function that takes a year, how do I get the minimum and maximum milliseconds for that year. (ie minimum being Jan 1 (Year) at 00:00.000 and maximum being Dec 31 11:59:59.999)?
Do I need to create a string representing those values and parse them, or is there a simpler method?
You could create a function like this, using January 1, 12:00 am and December 31, 11:59 pm as reference points:
function getMinMaxMilliseconds(year) { // Get seconds of January 1, 12:00 am of that year. let minMilliseconds = new Date(year, 0, 1, 0, 0, 0, 0).getTime(); // Get seconds of December 31, 11:59 pm 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));
With moment (using endOf()
and 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>
With native JavaScript Date:
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>
Moment has the startOf() and endOf() methods which can be used in the following way to get the milliseconds at start and end of a given year.
function getMillisecondRangeForYear(year) {
var date = moment({y: year});
return {
"min": date.startOf("year").valueOf(),
"max": date.endOf("year").valueOf()
};
}
You could create a date object as described here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date . For example:
new Date(yearInput, 1 [, 1 [, 0 [, 0 [, 0 [, 0]]]]]);
would create a date object for the minimum.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.