1. The implementation is very simple
As long as JavaScript is used well, all basic problems can be solved. And very simple.
Step 1 Instantiation
Instantiate an object time of a date class.
var time = new Date();
Step 2 to get the value
The object time uses its method to obtain the value. The method is very complete and simple. The commonly used ones are listed below.
method | illustrate |
---|---|
(); | Get the current year (2 digits + 1900) |
(); | Get the full year (4 digits) |
(); | Get the current month (0-11,0 represents January) |
(); | Get the current day (1-31) |
(); | Get the current week X (0-6,0 represents Sunday) |
(); | Get the current time (number of milliseconds starting from 1970/1/1) |
(); | Get the current number of hours (0-23) |
(); | Get the current number of minutes (0-59) |
(); | Get the current number of seconds (0-59) |
(); | Get the current number of milliseconds (0-999) |
(); | Get the current date (date only) |
(); | Get the current time (morning or afternoon + time) |
(); | Get date and time (date + time) |
2. Reference examples
1. No format required to obtain
If there is no special requirement for the format, you can directly use one method to give a complete time string "2022/4/20 3:13:39 pm". Refer to the following code:
function getSystemTime() { // Instantiate the date class var time = new Date(); //Print to get time (()); (()); (()); }
Printout:
2022/4/20
3:13:39 pm
2022/4/20 3:13:39 pm
2. Custom format acquisition
If a specific format is needed, we can customize the splicing, see the following code:
function getSystemTime() { // Instantiate the date class var time = new Date(); // Get the full year (4 digits) var year = (); // Get month (0-11,0 represents January) var month = () + 1; // Get date (1-31) var date = (); // Get hours var h = (); h = h < 10 ? '0' + h : h; // Get minutes var m = (); m = m < 10 ? '0' + m : m; // Get seconds var s = (); s = s < 10 ? '0' + s : s; //Test Print (year + "Year" + month + "moon" + date + "day " + h + ":" + m + ":" + s); // Merge back return(year + "Year" + month + "moon" + date + "day " + h + ":" + m + ":" + s) ; }
Printout:
April 22, 2022 15:13:39
3. Leap year calculation
The method of calculating leap years gives an example.
function is_leap_year() { // Get the full year (4 digits) var year = (); (year); return (0 == year % 4 && ((year % 100 != 0) || (year % 400 == 0))); } function test(){ if(is_leap_year()==true) { ("It's a leap year"); } else { ("Not a leap year"); } }
Printout:
2022
Not a leap year
This is the end of this article about the detailed explanation of how JavaScript gets system time. For more related content on JavaScript getting system time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!