How to use the add function from date-fns

Find comprehensive JavaScript date-fns.add code examples handpicked from public code repositorys.

date-fns.add is a function in the date-fns library for JavaScript that adds a specified amount of time to a given date object and returns a new date object.

50
51
52
53
54
55
56
57
58
59
if (set) {
  final = datefns.set(final, set);
}

if (diff) {
  final = datefns.add(final, diff); // date-fns.add() supports negative numbers as well
}

if (format) {
  try {
fork icon28
star icon313
watch icon7

+ 3 other calls in file

144
145
146
147
148
149
150
151
152
153
  if (alert.events.length === 0) {
    return true;
  }

  const lastEvent = alert.events[0];
  const timeout = add(new Date(lastEvent.createdAt), { seconds: alert.timeout });
  return isPast(timeout);
});

const { chartData, Datasets } = chart;
fork icon163
star icon0
watch icon0

How does date-fns.add work?

The date-fns.add function in the date-fns library for JavaScript is used to add a specified amount of time to a given date object and return a new date object. When called, date-fns.add takes two arguments: a date object representing the starting date, and an object representing the amount of time to add. The amount of time to add is specified using a set of properties, such as years, months, weeks, days, hours, minutes, and seconds. Each property should be an integer value indicating the amount of time to add. For example, to add 2 years, 3 months, and 4 days to a given date, you would call date-fns.add like this: php Copy code {{{{{{{ class="!whitespace-pre hljs language-php">const date = new Date(); const newDate = dateFns.add(date, { years: 2, months: 3, days: 4 }); date-fns.add returns a new Date object that represents the resulting date and time after the specified amount of time has been added to the starting date. The original date object is not modified. It's important to note that date-fns.add uses a "pure" functional programming approach, which means that it does not modify the input date object, and instead returns a new date object with the added time. This can help prevent bugs and make it easier to reason about the behavior of the function. In summary, date-fns.add is a function in the date-fns library for JavaScript that adds a specified amount of time to a given date object and returns a new date object. The amount of time to add is specified using an object with properties such as years, months, weeks, days, hours, minutes, and seconds.

69
70
71
72
73
74
75
76
77
78
79
80
});


run_test("render_now_returns_yesterday", () => {
    const today = date_2019;


    const yesterday = add(today, {days: -1});
    const expected = {
        time_str: $t({defaultMessage: "Yesterday"}),
        formal_time_str: "Thursday, April 11, 2019",
        needs_update: true,
fork icon1
star icon1
watch icon2

+ 23 other calls in file

70
71
72
73
74
75
76
77
78
79
novaData = new Date()

console.log(dateFns.format(novaData, "dd 'de' MMMM yyyy HH:mm:ss"))

// imutabilidade
const dataComDiasAdicionados = dateFns.add(novaData, {
    days: 4
})

console.log('novaData ', novaData)
fork icon1
star icon0
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const dateFns = require("date-fns");

// Create a date object representing the current date and time
const date = new Date();

// Add 2 years, 3 months, and 4 days to the current date
const newDate = dateFns.add(date, {
  years: 2,
  months: 3,
  days: 4,
});

// Log the original date and the new date to the console
console.log(`Original date: ${date}`);
console.log(`New date: ${newDate}`);

In this example, we first create a date object representing the current date and time using the Date constructor. We then call date-fns.add with the current date object and an object specifying the amount of time to add. In this case, we add 2 years, 3 months, and 4 days to the current date. date-fns.add returns a new date object that represents the resulting date and time after the specified amount of time has been added to the starting date. Finally, we log the original date and the new date to the console using template literals to display the dates as strings.

88
89
90
91
92
93
94
95
96
97
98
99


const DEFAULT_VESSEL_CONTROL_DAYS_UNTIL_DUE = 45;


const getVesselControlDueDate = (vessel, shipper) =>
  vessel.dischargeDate
    ? add(new Date(vessel.dischargeDate.replace(/-/g, '/')), {
        days:
          shipper.vesselControlDaysUntilDue ||
          DEFAULT_VESSEL_CONTROL_DAYS_UNTIL_DUE,
      })
fork icon0
star icon0
watch icon1

+ 44 other calls in file

32
33
34
35
36
37
38
39
40
41
} else {
  if (key == "name" || key == "mobile" || key == "last_followup.comment") {
    temp.push({ [key]: { $regex: req.query[key] } });
  } else if (key.includes("addedTime")) {
    let date = parseISO(req.query[key]);
    let date2 = add(date, { days: 1 });
    temp.push({ "last_followup.addedTime": { $gte: date, $lt: date2 } });
  } else if (key == "followup_list_length") {
    temp.push({ [key]: Number(req.query[key]) });
  }
fork icon0
star icon0
watch icon1

+ 36 other calls in file

65
66
67
68
69
70
71
72
73
74
if (["batch._id", "center._id", "teacher._id"].includes(key))
	Filter.push({ [key]: ObjectId(req.query[key]) });
else if (key == "start_time") {
	Filter.push({ start_time: { $gte: parseISO(req.query[key]) } });
} else if (key == "end_time") {
	Filter.push({ start_time: { $lt: add(parseISO(req.query[key]), { days: 1 }) } });
} else if (key == "topics") {
	temp = req.query[key]?.split(",").map((item) => ({ "topics": item }));
} else if (key == "ActualStatus") {
	Filter.push({ [key]: (req.query[key] == "true") ? true : false });
fork icon0
star icon0
watch icon1

+ 33 other calls in file

133
134
135
136
137
138
139
140
141
142
try {
  let taskName = document.getElementById('task-name').value

  // add day function is to fix the timeone offset I was encountering,
  // causing the selected date to be a day behind
  let taskDueDate = add(
    new Date(document.getElementById('task-duedate').value),
    { days: 1 }
  )
  if (taskDueDate == 'Invalid Date') {
fork icon0
star icon0
watch icon1

+ 14 other calls in file

24
25
26
27
28
29
30
31
32
33
34
35
    days: 2
}));


console.log(data);


const novaData = add(data, {
    days: 45,
    years: 2
});
console.log(novaData);
fork icon0
star icon0
watch icon0

+ 4 other calls in file

21
22
23
24
25
26
27
28
29
30
//Método add
//Faz operações aritiméticas (somar/subtrair) de um objeto de data. Ele não modifica o objeto original, cria um novo.
const addDate = new Date(2017, 3, 12);
console.log("new Date():", addDate);
//Mais 2 segundos, 1 dia e 10 anos
const newAddDate = add(addDate, {
    seconds: 2,
    days: 1,
    years: 10
});
fork icon0
star icon0
watch icon0

111
112
113
114
115
116
117
118
119
120
121
        assert.equal(actualDate, format.expected.date);
    }
});


run_test("get_localized_date_or_time_for_format returns correct localized date", () => {
    const date = add(date_2019, {years: -1});
    const languages = [
        {
            language: "en",
            expected: {
fork icon0
star icon0
watch icon0

+ 23 other calls in file

150
151
152
153
154
155
156
157
158
159

console.log('d.M.yyyy HH:mm:ss.SSS GMT XXX (z)', format(fnsDateZoned, 'd.M.yyyy HH:mm:ss.SSS GMT XXX (z)'));
console.log('LLL d, yyyy', format(fnsDateZoned, 'LLL d, yyyy'));

// Relative dates
const fnsDate30Days = add(fnsDate, { days: 30 });

console.log('+30 days', format(fnsDate30Days, 'LLL d, yyyy'));
console.log('relative', formatRelative(fnsDate30Days, fnsDate30Days));
console.log('duration', formatDistance(fnsDate30Days, fnsDate));
fork icon0
star icon0
watch icon2

Other functions in date-fns

Sorted by popularity

function icon

date-fns.format is the most popular function in date-fns (3838 examples)