Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theUnforgiven's avatar

moment JS and date formatting

Hi all,

I'm using Vue for some frontend stuff and I have a Vue Datepicker to select a start date. I thne have a duration box with 6-months 12 months and 18 months.

So I need to get what the end date will be based on selecting a start date and a duration.

So if I selected 1st Jan and 6 months the end dat should return 1st June.

How would one do this in moment as this is my first time using it to this degree.

0 likes
5 replies
topvillas's avatar
Level 46
let span = 6;
let duration = 'months';
let end = start.clone().add(span duration);

The clone part is important, Moment can catch you out by mutating dates.

theUnforgiven's avatar

@topvillas - I think i need to format how it comes back from the datepicker, as it's currently 15th May 2020

topvillas's avatar

I'm not 100% sure but Moment should be able to parse that.

let start = moment(dateFromDataPicker);

if not use ...

let start = moment(dateFromDatePicker, 'Do MMM YYYY');

Docs about date parsing are here. https://momentjs.com/docs/#/parsing/

theUnforgiven's avatar

It's cool, I changed the formatting from the flatPickr Vuejs component so now it's showing as a valid moment date.

theUnforgiven's avatar

I did as follows:

 if(start.isValid()) {
        let span = this.form.duration; // this is passed from select as a number and all in months
        end = start.add(span, 'M').subtract(1, "days"); // So figured I could use that number and M for months.

        this.tenancyDuration = 'Agreement will end on: ' + end.format('Do MMMM YYYY');
} else {
        this.tenancyDuration = '';
}

Seems to work a treat now.

Please or to participate in this conversation.