Encapsulate time processing functions, allowing you to process time business more quickly

Including obtaining the current date, obtaining the specified date, calculating the date difference, calculating the month difference between two dates, and obtaining the number of days in the current month

1. Get the current date

Receive the parameter format
@return to specify the format date

currentDate(format = 'yyyy-mm-dd') {
    
    
	const date = new Date()
	const year = date.getFullYear()
	const month = numberComplement(date.getMonth() + 1)
	const day = numberComplement(date.getDate())
	if (format === 'yyyy-mm-dd') {
    
    
		return `${
      
      year}-${
      
      month}-${
      
      day}`
	}
	if (format === 'yyyy/mm/dd') {
    
    
		return `${
      
      year}/${
      
      month}/${
      
      day}`
	}
	return `${
      
      year}${
      
      month}${
      
      day}`
}

2. Get the specified date

Receive parameters targetDate, day
targetDate: target start date
day: date a few days after the target
, such as targetDate=2023-03-07, day=7
@return 2023-03-14

getAppointDate(targetDate, day) {
    
    
	let result = new Date(new Date(targetDate).getTime() + 24 * 60 * 60 * 1000 * day);
	return `${
      
      result.getFullYear()}-${
      
      numberComplement(result.getMonth() + 1)}-${
      
      numberComplement(result.getDate())}`;
}

3. Calculate the date difference

Calculate how many days are between two dates
Receive parameters startDate, endDate
@return days (difference in days)

getDaysDifference(startDate, endDate) {
    
    
	const sDate = Date.parse(startDate);
	const eDate = Date.parse(endDate);

	const days = (sDate - eDate) / (24 * 60 * 60 * 1000);
	return days;
}

4. Calculate the month difference between two dates

Receive parameters startDate, endDate

diffMonths(startDate, endDate) {
    
    
	let startYear = startDate.split("-")[0]
	let endYear = endDate.split("-")[0]
	let startM = startDate.split("-")[1]
	let endM = endDate.split("-")[1]
	let startMonth = startYear + startM
	let endMonth = endYear + endM
	
	if (startMonth > endMonth) {
    
    
		let diffYear = startYear - endYear
		let diffMonth = startM - endM
		return diffYear * 12 + diffMonth
	} else if (startMonth < endMonth) {
    
    
		let diffYear = endYear - startYear
		let diffMonth = endM - startM

		return diffYear * 12 + diffMonth
	} else {
    
    
		return 0
	}
}

5. Get the number of days in the current month

@return days

getDays() {
    
    
	const date = new Date()
	return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}

If you find it useful, feel free to give it a thumbs up, thank you for
following me and sharing technical dry goods from time to time~

Guess you like

Origin blog.csdn.net/weixin_45295253/article/details/129383179