Yesterday, I saw a piece of news that the famous former CCTV big shot Li Yong died all over the Internet. Everyone’s attention is on li yong’s death itself, but my concern is that it happened because Li Yong was a heavy drinker. What about drinking? Drinking is a traditional custom of the Chinese nation, and almost every Chinese will drink. No matter in the Spring Festival or many occasions, wine is the best catalyst to adjust the atmosphere. But back in February, Nature published an article suggesting that drinking alcohol may increase your risk of cancer. Of course, I also read this article, speak very advanced, do not understand. But knowing that drinking is wrong.

I have encountered a lot of strange requirements in development recently, mostly related to time. Where am I? Let’s summarize some of the techniques for using time in JS.

First, date formatting

The Date object is used to handle dates and times.

Date objects can be defined by the new keyword. The following code defines a Date object named myDate:

letdate = new Date(); // Tue Oct 29 2018 21:09:05 GMT+0800Copy the code

Just like the operation above. However, the time format of Tue Oct 29 2018 21:09:05 GMT+0800 is not intuitive for a user. It should be processed to make it intuitive for users to watch, consult or store it in the database.

1. Format Date as a timestamp

Timestamp is a storage method often used in program development, here we can directly convert;

letdate = new Date(); // Tue Oct 29 2018 21:09:05 GMT+0800lettimestamp =Date.parse(date); / / 1540818545000Copy the code

2. Convert the timestamp to Date

Date objects are converted to timestamps, and timestamps are converted to Date objects.

letdate = new Date(1540818545000); //Mon Oct 29 2018 21:09:05 GMT+0800Copy the code

3. Format Date as year, month and day

A lot of requirements inside want to convert the time into XXXX xx month XX, XXXX-XX-XX and so on. Because it’s a little bit more intuitive. Take a look at the following code:

let date = new Date();
console.log("year:",date.getFullYear()); // 2018
console.log("month:",date.getMonth()+1); // 10
console.log("day:",date.getDate()); // 29
console.log("hours:",date.getHours()); // 21
console.log("minute:",date.getMinutes()); // 9
console.log("second:",date.getSeconds()); // 5
console.log("millsecond:",date.getMilliseconds()); / / 0Copy the code

It is worth noting here:

  • Month is counted from 0, so you need to add 1
  • Days to obtaingetDate()Rather thangetDay().

Ok, let me show you the complete code:

      function formatDate () {
        let date = new Date()
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        m = m < 10 ? ('0' + m) : m
        let d = date.getDate()
        d = d < 10 ? ('0' + d) : d
        let h = date.getHours()
        h = h < 10 ? ('0' + h) : h
        let minute = date.getMinutes()
        let second = date.getSeconds()
        minute = minute < 10 ? ('0' + minute) : minute
        second = second < 10 ? ('0' + second) : second
        return y + The '-' + m + The '-' + d + ' ' + h + ':' + minute + ':' + second
      }
Copy the code

4. Convert year, month and day to Date().

The operation is actually quite simple:

let date = new Date("2018-01-01"); // Mon Jan 01 2018 00:00:00 GMT+0800Copy the code

It could even go like this:

let date = new Date("2018-01"); // Mon Jan 01 2018 08:00:00 GMT+0800let date5 = new Date("The 2018-01-01 10:20:25"); // Mon Jan 01 2018 10:20:25 GMT+0800Copy the code

It is worth noting here that if the value is passed like this:

let date2 = new Date("1 January 2018"); // Invalid Date
Copy the code

If you are going to do it, the format should be xxxx-xx-XX HH :mm: SS.

Two, some advanced operation of time:

1. Get tomorrow

function getLastDay() {letdate = new Date(); // Get the current time date.setDate(date.getDate()+1); // Set the number of days +1return formatDate(date);
}
Copy the code

2. Monday

function getWeekFristDay() {let nowDate = new Date();
  letweekFirstDay = new Date(nowDate - (nowDate.getDay() - 1) * 86400000); // Mon Oct 29 2018 21:09:05 GMT+0800return formatDate(weekFirstDay);
}
Copy the code

3. Get a week ago

function getWeekLater() {let now = new Date();
  let date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
  return formatDate(date);
}
Copy the code

4. The number of days between the two dates

function dateDifference(sDate1, sDate2) {
   let sDate1 = Date.parse(sDate1);
   let sDate2 = Date.parse(sDate2);
   let dateSpan = sDate2 - sDate1;
   dateSpan = Math.abs(dateSpan);
   iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
   return iDays 
}
Copy the code

Date object all methods:

GetDate () returns the day of the month (1-31) from the Date object.

GetDay () returns a day of the week (0 to 6) from the Date object.

GetMonth () returns the month (0 to 11) from the Date object.

GetFullYear () returns the year as four digits from the Date object.

GetYear () use getFullYear() instead.

GetHours () returns the hour of the Date object (0 to 23).

GetMinutes () returns the minutes of the Date object (0 to 59).

GetSeconds () returns the number of seconds (0 to 59) of the Date object.

GetMilliseconds () returns the milliseconds (0 to 999) of the Date object.

GetTime () returns the number of milliseconds since January 1, 1970.

GetTimezoneOffset () returns the minute difference between the local time and Greenwich Mean Time (GMT).

GetUTCDate () returns the day of the month (1-31) from the Date object based on world time.

GetUTCDay () returns the day of the week (0 to 6) from the Date object based on world time.

GetUTCMonth () returns the month (0 to 11) from the Date object based on world time.

GetUTCFullYear () returns the four-digit year from the Date object based on world time.

GetUTCHours () returns the hour of the Date object based on world time (0 to 23).

GetUTCMinutes () returns the minute of the Date object based on world time (0 to 59).

GetUTCSeconds () returns the number of seconds (0 to 59) of the Date object based on world time.

GetUTCMilliseconds () returns the milliseconds (0 to 999) of the Date object based on the world time.

Parse () returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string).

SetDate () sets the Date of the month (1 to 31) in the Date object.

SetMonth () Sets the month (0 to 11) in the Date object.

SetFullYear () sets the year (four digits) in the Date object.

SetYear () use setFullYear() instead.

SetHours () sets the hours (0 to 23) in the Date object.

SetMinutes () sets the minutes (0 to 59) in the Date object.

SetSeconds () sets the number of seconds (0-59) in the Date object.

SetMilliseconds () sets milliseconds (0 to 999) in the Date object.

SetTime () sets the Date object in milliseconds.

SetUTCDate () sets the day (1-31) of the month in the Date object based on universal time.

SetUTCMonth () sets the month (0 to 11) in the Date object based on universal time.

SetUTCFullYear () sets the year (four digits) in the Date object based on universal time.

SetUTCHours () sets the hour (0 to 23) in the Date object based on world time.

SetUTCMinutes () sets the minutes (0 to 59) in the Date object based on universal time.

SetUTCSeconds () sets the seconds (0 to 59) in the Date object based on universal time.

SetUTCMilliseconds () sets the milliseconds (0 to 999) in the Date object based on the universal time.

ToSource () returns the source code for this object.

ToString () converts a Date object to a string.

ToTimeString () converts the time part of the Date object to a string.

ToDateString () converts the Date part of the Date object to a string.

ToGMTString () use the toUTCString() method instead.

ToUTCString () converts the Date object to a string based on world time.

ToLocaleString () converts the Date object to a string based on the local time format.

ToLocaleTimeString () converts the time part of the Date object to a string based on the local time format.

ToLocaleDateString () converts the Date part of the Date object to a string based on the local time format.

UTC() returns the number of milliseconds in universal time from January 1, 1997 to the specified date.

ValueOf () returns the original valueOf the Date object.

Fourth, a final point worth noting is:

4.1 ‘-‘ is not recognized on some ios machines

Solutions:

let data = '2017-01-01'
data.replace(/-/g,'/')
Copy the code

Just replace ‘-‘ with ‘/’.

4.2、 toJSON/toISOString

Said in the last

This is by far the simplest technical article I’ve written. This is mainly used in recent projects. Of course, there may be some writing methods that I haven’t thought of in a short time. Anyway, we’ll add it when we think about it. I suddenly don’t know what to write recently, so I have to find a common one to write. Time is about the same, the talk is about the same, to exercise.