Share 8 cold knowledge about new Date(), you need to know

b685d3510562d99eaa539f6fb482e2e4.jpeg

The new Date() constructor is the devil - oh, I'm afraid of it! This has caused me to make a lot of mistakes at work, some of them really weird.

We have to be very careful with it, otherwise we can easily fall into its trap.

1. The Safari browser does not support formatted dates in the form of YYYY-MM-DD

do you know? The "Safari" browser does not support initialization times of the form "YYYY-MM-DD". Many browsers other than it, such as Chrome, perfectly support this format.

If you write code like this, your application will get an invalid date error in the "Safari" browser.

new Date('2023-05-28') // Invalid Date

To handle this properly, we need to initialize the time in the form "YYYY/MM/DD".

new Date('2023/05/28')

2. Use 0 as the starting index of the month

How should we initialize the date May 28, 2023?

const d = new Date(2023, 4, 28)


console.log(d.getMonth()) // 4

We pass 4 as the second parameter to Date, but why not 5?

Ah! I hate this feature. When dealing with months, the date starts with 0 for January, 1 for February, and so on. This function is terrible, very messy and buggy.

3. Pitfalls about its automatic date correction

It's hard to guess what the real date represented by the code below is.

Maybe a February 2023 date? But it's weird that February doesn't have 32 days, so what is it?

const d = new Date(2023, 1, 32)

Let's write a function that parses a date object.

const parseDate = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1 //Since the index of the month starts from 0, we need to add 1
  const day = date.getDate()


  return { year, month, day }
}


console.log(parseDate(new Date(2023, 1, 32)))
/*
{
  "year": 2023,
  "month": 3,
  "day": 4
}
*/

Oh, and the new date (2023, 1, 32) is March 4, 2023, which is outrageous.

4. Can't easily format a date?

How to convert an array to a string in a specified format? Very simple, we can use the join method of the array.

const array = [ '2023', '5', '28' ]


console.log(array.join('/')) // 2023/5/28
console.log(array.join('-')) // 2023-5-28
console.log(array.join(':')) // 2023:5:28

But the Date object does not provide a direct and convenient way to format the date, so we have to write the code to do it ourselves.

const formatDate = (date, format = '/') => {
  return date.getFullYear() + format + (date.getMonth() + 1) + format + date.getDate()
}


formatDate(new Date(2023, 4, 28), ':') // 2023:5:28
formatDate(new Date(2023, 4, 28), '/') // 2023/5/28
formatDate(new Date(2023, 4, 28), ':') // 2023-5-28

5. Unable to determine if date object is valid

Just like the above example, since the Date object will automatically fix the date, we cannot judge whether a date is really valid.

const d = new Date(2023, 15, 1) // this is a date that does not exist


formatDate(d) // 2024/4/1

6. The date of string type cannot be parsed correctly

Many times we will initialize the date by passing a date string because it is much more convenient to use than new Date(2023, 4, 28) .

const d1 = new Date('2023-5-28')


console.log(formatDate(d1)) // 2023/5/28

There are pitfalls here too, my friend, we must be careful.

const d2 = new Date('5-28-2023')


console.log(formatDate(d2)) // 2023/5/28

If you pass in such a date, you will get an invalid error warning.

const d3 = new Date('28-5-2023') // Invalid Date
const d4 = new Date('2023-28-5') // Invalid Date

7. Unable to determine whether Date is a leap year

Wow, sometimes at work we need to determine if a year is a leap year, which is a bit of a hassle because the Date object doesn't provide an object method to do this either.

const isLeapYear = (date) => {
  const year = date.getFullYear()
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}


isLeapYear(new Date(2023, 4, 28)) // false
isLeapYear(new Date(2020, 4, 28)) // true

8. What week of the year is the new date (xx, xx, xx) in?

The Date object provides functions to get the year, month, day, hour, minute, etc.

How do we determine what week of the year a date is? We can only accomplish this goal through complex calculations.

const getWeekNumber = (date) => {
  // Creates a new Date object, set to a copy of the given date
  const newDate = new Date(date.getTime())
  // Set the time part of the date object to 0 so that only the date is considered
  newDate.setHours(0, 0, 0, 0)
  // Sets the date object to the first day of the year
  newDate.setDate(1)
  newDate.setMonth(0)
  // Gets the day of the week for the first day (0 for Sunday, 1 for Monday, etc.
  const firstDayOfWeek = newDate.getDay()
  // Calculates the difference in days from a given date to the start of the first week
  const diff = (date.getTime() - newDate.getTime()) / (24 * 60 * 60 * 1000)
  // Determines the start date of the first week according to the ISO 8601 standard
  let weekStart = 1 - firstDayOfWeek
  if (firstDayOfWeek > 4) {
    weekStart += 7 // If the first day is a Friday or later, move the first week back by one week
  }
  // Calculate week number (rounded down)
  const weekNumber = Math.floor((diff + weekStart) / 7) + 1
  return weekNumber
}


getWeekNumber(new Date(2023, 4, 28)) // 22

This is a common calculation that uses the ISO 8601 standard to calculate the week of the year for a date.

But obviously, it's too complicated for me to understand this function.

write at the end

Date objects have a lot of weird behavior, we can use some powerful libraries to help us. For example Moment.js, Day.js, date-fns, etc.

I hope today's content is helpful to you, thank you for reading, and wish you a happy programming!

learn more skills

Please click the public number below

ab5af5b93cd10ed2d7f78932ab3a5234.gif

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/131733373