📜  typescript date set time end of day - TypeScript (1)

📅  最后修改于: 2023-12-03 15:20:42.940000             🧑  作者: Mango

Typescript Date Set Time End of Day

In Typescript, you can use the setHours() method to set the time to the end of the day in a Date object. This can be useful if you need to get the last moment of a specific day for comparison or manipulation purposes.

Here is an example code snippet that sets the time to the end of the day and returns a new Date object:

const date = new Date();
date.setHours(23, 59, 59, 999); // set time to end of day
const endOfDay = new Date(date.getTime());

In this code, we first create a new Date object and then use the setHours() method to set the time to 23:59:59.999, which is the last moment of the day. We then create a new Date object with the same time value as the modified date object. This ensures that we get a new Date object that represents the end of the day, rather than modifying the original date object.

You can also define a utility function to simplify this process, as shown below:

function getEndOfDay(date: Date): Date {
  const endOfDay = new Date(date.getTime());
  endOfDay.setHours(23, 59, 59, 999);
  return endOfDay;
}

This function takes a Date object as an argument and returns a new Date object that represents the end of the day.

Now you can easily get the end of the day for any Date object by calling the getEndOfDay() function:

const today = new Date();
const endOfDay = getEndOfDay(today);
console.log(`End of day: ${endOfDay}`);

This will output a string representation of the end of the day, which should be 23:59:59.999 for the current day.

In conclusion, setting the time to the end of the day in Typescript is simple using the setHours() method. By defining a utility function, you can easily get the end of the day for any Date object in your code.