Actually, i am stuck in one problem that is about Date.
I want to subtract and plus the date in react native.
is there any solution about it.
I have used Moment.js but the error occurs in it so please help me.
Thank you in advance
Actually, i am stuck in one problem that is about Date.
I want to subtract and plus the date in react native.
is there any solution about it.
I have used Moment.js but the error occurs in it so please help me.
Thank you in advance
check below working example of add and subtract day, month and date using moment:
For Day
let tomorrow = new Date();
tomorrow = moment(tomorrow).add(1, 'day').format('YYYY-MM-DD'); // for specific format
let today = moment(new Date()).format('YYYY-MM-DD');
let tomorrow = new Date();
tomorrow = moment(tomorrow).add(1, 'day').format('YYYY-MM-DD');
For Month
moment(currentMonth).add(1, 'month');
moment(currentMonth).subtract(1, 'month');
For Date
let now = "14/11/2016";
let then = "03/12/2017";
let diff = moment(now,"DD/MM/YYYY").diff(moment(then,"DD/MM/YYYY"));
let duration = moment.duration(diff);
let result = duration.format("hh:mm:ss");
Please refer detailed date difference: https://stackoverflow.com/a/18624295/6592263
EDIT (Not tested)
To get Month
let d = moment(new Date());
d.month(); // month number
d.format('ddd MMM DD YYYY');
TO get Year
let d = moment(new Date());
d.year() // year
If you want to take today date and add a year, month or a day, you can first create a date object, access the relevant properties, and then use them to create a new date object:
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDate();
const c = new Date(year + 1, month, day) // PLUS 1 YEAR
const d = new Date(year, month + 1, day) // PLUS 1 MONTH
const f = new Date(year, month, day + 1) // PLUS 1 DAY
My use case was to get end date after adding some months. This works without using moment.
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
function add_months_todate(dt, no_of_month)
{
return new Date(dt.setMonth(dt.getMonth() + no_of_month));
}
start_date = new Date();
end_date = add_months_todate(new Date(), 10);
console.log("START DATE",formatDate(start_date));
console.log("END DATE",formatDate(end_date));
Reference :https://www.w3resource.com/javascript-exercises/javascript-date-exercise-43.php