Skip to content

Instantly share code, notes, and snippets.

@arturslab
Created July 5, 2024 20:23
Show Gist options
  • Save arturslab/e4dcb5e8a797b825f0313ab51ad86e01 to your computer and use it in GitHub Desktop.
Save arturslab/e4dcb5e8a797b825f0313ab51ad86e01 to your computer and use it in GitHub Desktop.
Simple Vue.js helper that allows you to calculate a new date that is shifted by a specified number of days, months, or years relative to a given date (or the current date if no date is provided)
import moment from 'moment';
/**
* Get date before or after n days, months or years
* @param n number of days, months or years
* @param type days, months or years
* @param date date to start from (default is current date). May be string (example: '2024-01-25') or Date object
* @param format return date format (default is 'YYYY-MM-DD')
*/
export const getAdjustedDate = (n: number, type: string, date?: any, format?: string) => {
date = date || new Date();
format = format || 'YYYY-MM-DD';
const newDate = new Date(date);
if (type === 'days') {
newDate.setDate(newDate.getDate() + n);
} else if (type === 'months') {
newDate.setMonth(newDate.getMonth() + n);
} else if (type === 'years') {
newDate.setFullYear(newDate.getFullYear() + n);
}
return moment(newDate).format(format);
};
import { defineComponent, ref, onMounted } from 'vue';
import moment from 'moment';
import { getAdjustedDate } from './path/to/your/helper/file/helpers.ts'; // Make sure the path is correct
export default defineComponent({
name: 'MyComponent',
setup() {
const dateToday = ref(moment().format('YYYY-MM-DD'));
const tenDaysLater = ref('');
const twoMonthsEarlier = ref('');
const oneYearLaterFormatted = ref('');
onMounted(() => {
tenDaysLater.value = getAdjustedDate(10, 'days');
twoMonthsEarlier.value = getAdjustedDate(-2, 'months', '2024-01-25');
oneYearLaterFormatted.value = getAdjustedDate(1, 'years', undefined, 'DD-MM-YYYY');
});
return {
dateToday,
tenDaysLater,
twoMonthsEarlier,
oneYearLaterFormatted
};
},
template: `
<div>
<p>Today's Date: {{ dateToday }}</p>
<p>Date 10 Days Later: {{ tenDaysLater }}</p>
<p>Date 2 Months Earlier from 2024-01-25: {{ twoMonthsEarlier }}</p>
<p>Date 1 Year Later (Formatted as DD-MM-YYYY): {{ oneYearLaterFormatted }}</p>
</div>
`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment