Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน Date.setSeconds() ใน JavaScript

ฟังก์ชัน setSeconds() ของออบเจกต์ Date รับจำนวนเต็มแทนวินาที และแทนที่ค่าวินาทีในวันที่ปัจจุบันด้วยค่านั้น (ใช้เวลาท้องถิ่น)

ไวยากรณ์

dateObj.setSeconds(seconds);

ตัวอย่าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var dateObj = new Date('september 26, 89 5:4:25:96');       document.write("วันที่ปัจจุบัน: "+dateObj.toUTCString());       document.write("<br>");       dateObj.setSeconds(9);       document.write("วันที่หลังตั้งค่าวินาที: "+dateObj.toUTCString());    </script> </body> </html>

ผลลัพธ์

วันที่ปัจจุบัน: Mon, 25 Sep 1989 23:34:25 GMT วันที่หลังตั้งค่าวินาที: Mon, 25 Sep 1989 23:34:09 GMT

ตัวอย่าง: ตั้งค่าวินาทีโดยไม่ได้ระบูวินาทีตอนสร้าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var dateObj = new Date('26, September, 1989 4:25');       dateObj.setSeconds(55);       document.write(dateObj.toString());    </script> </body> </html>

ผลลัพธ์

Tue Sep 26 1989 04:25:55 GMT+0530 (India Standard Time)

ตัวอย่าง: ใช้กับวันที่ปัจจุบัน

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var dateObj = new Date();       dateObj.setSeconds(55);       document.write(dateObj.toString());    </script> </body> </html>

ผลลัพธ์

Thu Oct 18 2018 18:44:55 GMT+0530 (India Standard Time)

คุณสมบัติเพิ่มเติม:

  • รองรับพารามิเตอร์ที่ 2: setSeconds(seconds, ms)
  • ค่าเกิน 59 จะเพิ่มนาทีอัตโนมัติ
  • ค่าลบจะย้อนเวลากลับ
  • เวอร์ชัน UTC: setUTCSeconds()