This is the 4th day of my participation in the August More Text Challenge

Of course, there are many time-related methods in JavaScript, but we seldom use them. For example, I can’t remember them, so I search them when I use them. However, there are always similar articles recommended on the Internet, and sometimes I miss many useful methods. Today, I’ll summarize the relevant methods, and you’ll never have to worry about using them again.

Date formatting

toLocaleDateString()

ToLocaleDateString () is a date formatting method I personally like because it’s convenient and we don’t have to do the traditional method of getting a single day and month and then concatenating it.

let time = new Date()
time.toLocaleDateString() / / "2021/8/22"
Copy the code

Unfortunately, this method may behave differently on each browser, and I haven’t tested it here, but if you only use one browser, you can use this method.

toTimeString()

This method corresponds to the method above, which gets the date, and this method gets the time

let time = new Date()
time.toTimeString() // "23:53:58 GMT+0800"
Copy the code

toLocaleString()

There’s also a two-in-one one that gets the date and time

let time = new Date()
time.toLocaleString() // "2021/8/22 23:55:26 am"
Copy the code

The traditional method

The traditional method of obtaining date and time is also documented here

function getNowFormatDate() {
  var date = new Date(a);var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}
Copy the code

Compatibility issues

Here to record a compatibility problem, sometimes the back end return time may return such format 2021-08-09 18:00:00, then if we need to obtain the corresponding time format, we will use the following method

new Date('the 2021-08-09 18:00:00')
Copy the code

However, I found a compatibility issue when I used it. On Windows, the above method worked fine, but on Mac safari, it had a problem

// safari
new Date('the 2021-08-09 18:00:00') // -> Invalid Date
Copy the code

I’m not trying to see if this will happen on iPhone, but I guess it will happen the same way, because Safari doesn’t support this time format, so we need to convert it to 202/08/09 18:00:00

let time = 'the 2021-08-09 18:00:00'
time = time.replace(/-/g.'/')
console.log(new Date(time)) // -> Mon Aug 09 0202 18:00:00 GMT+0800 (CST) = $3
Copy the code