Skip to main content

The use of date functions in Js and the formatting of dates

 In daily coding, date data is often formatted, and Date objects are used to process dates and times. This article first introduces the Date object, and then deepens its understanding and practical application through a small case of formatting a date, including function use cases such as year, month, time, etc., friends who need it can read and refer to it.

Several ways to create Date objects

   let date=new Date();
        //
        date=new Date("may 18,2022 11:12:12");
        //
        date=new Date("may 19,2022 11")//Thu May 19 2022 00:00:00
        //
        date=new Date("may 19,2022 11:")//Thu May 19 2022 11:00:00
        //
        date=new Date(2022,12,30,11,20,20)//Mon Jan 30 2023 11:20:20
        //
        date=new Date(2022,08,05,20)//Mon Sep 05 2022 20:00:00
        //
        date=new Date(100002220000)
        console.log(date);
Common methods of Date objects
  let date=new Date(2333333333333);//Thu Dec 10 2043 12:08:53
        //
        date=date.getYear();//143
        //
        date=date.getFullYear();//2043
        //
        date=date.getMonth();//11
        //
        date=date.getDate();//10
        //
        date=date.getDay();//4
        //
        date=date.getHours();//12
        //
        date=date.getMinutes();//8
        //
        date=date.getSeconds();//53
        //
        date=date.getMilliseconds();//333
        //
        date=date.toLocaleDateString();//2043/12/10
        //
        date=date.toLocaleString();//2043/12/10 PM12:08:53
        //
        date=date.toLocaleTimeString();//PM12:08:53
       
        console.log(date);
format Date
let date=new Date(2333333333333);
        function formatDate(d){
            let year=date.getFullYear();
            let month=date.getMonth()+1;
            let day=date.getDate();
            let hour=date.getHours();
            let minute=date.getMinutes();
            let second=date.getSeconds();
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        }
        console.log(formatDate(date));//2043-12-10 12:8:53
Note: The return value for the month is 0-11.

Comments

Popular posts from this blog

A simple understanding of ES6 iterators

 What is an iterator?An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed.ES6 created a new traversal command for...of loop, which natively has a data structure with the iterator interface (which can be traversed with for...of). Contains Array, Arguments, Set, Map, String, TypedArray, NodeList. Of course, you can also implement this interface manually, which is convenient for practical use.