What is moment().miliseconds() in JavaScript?
Overview
In the moment.js package, the miliseconds() method returns the number of milliseconds present in a date or time. It can also be used to set the milliseconds of a date or time.
Note: The
milliseconds()method is the same asmillisecond()method.
Syntax
// get millisecondsmoment(datetime).milliseconds()// set millisecondsmoment(datetime).milliseconds(Number)
Syntax for milliseconds() method of moment.js
Parameters
datetime: This is the date or time we want to get or set its milliseconds.
Number: This is the number of seconds we want to set our date or time. It can only be from 0 to 999.
Return value
This method returns a millisecond from 0 to 999. If this range is exceeded, the value returned will be bubbled up to the seconds.
Code example 1
Let's look at the code below:
// require the moment moduleconst moment = require("moment")// create some dates and timeconst date1 = moment(); // current date and timeconst date2 = moment('2020.01.01', 'YYYY.MM.DD')const date3 = moment([2010, 1, 14, 15, 25, 50, 125])const date4 = moment(new Date) // current date and timeconst time1 = moment(1318781876406)const time2 = moment({hour: 20, minute: 20, second: 34})// get the milliseconds of the time and datesconsole.log(date1.milliseconds())console.log(date2.millisecond())console.log(date3.milliseconds())console.log(date4.milliseconds())console.log(time1.millisecond())console.log(time2.milliseconds())
Code explanation
In the code above:
- Line 2: We require the
momentpackage. - Lines 5 to 10: We create some dates and times using the
momentpackage. - Lines 13 to 18: We use the
milliseconds()method and get the milliseconds of the dates and times created.
Code example 2
Let's look at the code below:
// require the moment moduleconst moment = require("moment")// create some dates and timeconst date1 = moment(); // current date and time// get the millisecondsconsole.log(date1.milliseconds())// now set the millsecondsdate1.milliseconds(20)// get the milliseconds againconsole.log(date1.milliseconds())
Code explanation
In the code above:
- Line 2: We require the
momentmodule. - Line 5: We create a new date and time that is the current date and time.
- Line 8: We use the
milliseconds()method to get the milliseconds of the date we created and print it to the console. - Line 11: We set the milliseconds to a new value
20. - Line 14: We use the
milliseconds()method to get the new milliseconds of the date we created, and print the result to the console.