दिनांक को प्रारूपित करने के लिए जावास्क्रिप्ट प्रोग्राम

इस उदाहरण में, आप एक जावास्क्रिप्ट प्रोग्राम लिखना सीखेंगे जो एक तारीख को प्रारूपित करेगा।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावास्क्रिप्ट प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावास्क्रिप्ट अगर … और स्टेटमेंट
  • जावास्क्रिप्ट दिनांक और समय

उदाहरण 1: दिनांक को प्रारूपित करें

 // program to format the date // get current date let currentDate = new Date(); // get the day from the date let day = currentDate.getDate(); // get the month from the date // + 1 because month starts from 0 let month = currentDate.getMonth() + 1; // get the year from the date let year = currentDate.getFullYear(); // if day is less than 10, add 0 to make consistent format if (day < 10) ( day = '0' + day; ) // if month is less than 10, add 0 if (month < 10) ( month = '0' + month; ) // display in various formats const formattedDate1 = month + '/' + day + '/' + year; console.log(formattedDate1); const formattedDate2 = month + '-' + day + '-' + year; console.log(formattedDate2); const formattedDate3 = day + '-' + month + '-' + year; console.log(formattedDate3); const formattedDate4 = day + '/' + month + '/' + year; console.log(formattedDate4);

आउटपुट

 08/26/2020 08-26-2020 26-08-2020 26/08/2020

उपरोक्त उदाहरण में,

1. new Date()वस्तु वर्तमान तिथि और समय देती है।

 let currentDate = new Date(); console.log(currentDate); // Output // Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)

2. getDate()विधि निर्दिष्ट तिथि से दिन लौटाती है।

 let day = currentDate.getDate(); console.log(day); // 26

3. getMonth()विधि निर्दिष्ट तिथि से महीना लौटाती है।

 let month = currentDate.getMonth() + 1; console.log(month); // 8

4. 1 में जोड़ा जाता है getMonth()विधि क्योंकि महीने से शुरू होता है 0 । इसलिए, जनवरी 0 है , फरवरी 1 है , और इसी तरह।

5. getFullYear()निर्दिष्ट तिथि से वर्ष लौटाता है।

 let year = currentDate.getFullYear(); console.log(year); // 2020

फिर आप विभिन्न स्वरूपों में दिनांक प्रदर्शित कर सकते हैं।

दिलचस्प लेख...