0

I am building a money manager app with React Native for the purpose of the exam and I have a problem with storing dates. App should be able to list daily, monthly and weekly transactions.

Can someone help me with the schema of a transaction, especially how to handle dates? My transaction has the following attributes:

  • amount
  • type (income or expense)
  • account (credit card or cash)
  • category
  • date

I am getting the date with new Date() but its value changes every millisecond and I need my transactions of the same day to to have the same date.

Also if you have a better idea how to design my transaction object, please don't hesitate to tell me.

senthil balaji
  • 588
  • 4
  • 18
  • 1
    I'd stick to storing timestamps, the problem you need to solve is how to determine whether two timestamps are on the same day, in the same week, or in the same month. Once you create a new `Date` based on the stored timestamp, you can simply extract and compare the year, month and day of month, this solves 2 out of 3; as for the week you need an algorithm for that anyway. –  Sep 19 '20 at 10:56
  • Format the date to string. there are multiple ways you could do this. use `moment.js` (easiest way) or write a js function which will do the transformation. And data modelling the schema is purely based on requirement. – senthil balaji Sep 19 '20 at 10:58

1 Answers1

1

Here's a way to compare whether two transactions that use a Date object / store a milliseconds timestamp happened on the same week, day or month.

const x = new Date("2020-09-19 11:55:30");
const y = new Date("2020-09-17 14:12:44");

Date.prototype.getWeekNumber = function() {
  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
  var dayNum = d.getUTCDay() || 7;
  d.setUTCDate(d.getUTCDate() + 4 - dayNum);
  var yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
  return Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
};

function sameMonth(a, b) {
  return a.getFullYear() == b.getFullYear() && a.getMonth() == b.getMonth();
}

function sameDay(a, b) {
  return sameMonth(a, b) && a.getDate() == b.getDate();
}

function sameWeek(a, b) {
  return a.getFullYear() == b.getFullYear() && a.getWeekNumber() == b.getWeekNumber();
}

console.log(x);
console.log(y);
console.log("same month:", sameMonth(x, y));
console.log("same day:", sameDay(x, y));
console.log("same week:", sameWeek(x, y));

Source for week number function: https://stackoverflow.com/a/6117889/5734311 Also, momentjs has a .week() function.