0

I have this code which works fine. It gives me todays date in a specific format.

function fetchTime() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  return (today);
}

I'm also trying to get today's date minus 1 month. I thought this would be simple, I just removed the +1. So I have this code:

function fetchTime() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth();
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  return (today);
}

This gives me the output 2019-00-17 which should be 2018-12-17

Can anyone tell me the right way to do this? My question is specific to getting the date out in the required format, whereas most examples I have seen do not output the right format as part of the date change.

Learning2Code
  • 521
  • 9
  • 21
Jimmy
  • 12,087
  • 28
  • 102
  • 192
  • @Codeer The trouble with that is its not giving me the right output format. – Jimmy Jan 17 '19 at 15:31
  • 1
    Why not have a formatTime function that accepts a Date parameter. Then you could pass the current date, or the current date a month prior, or any date. – Learning2Code Jan 17 '19 at 15:37
  • @Learning2Code That would be amazing but I think that's a bit beyond me quite honestly, trying to get even a simple example working – Jimmy Jan 17 '19 at 15:38
  • I don't think the question is a duplicate, because OP is specifically asking about format. But yes the accepted answer should call a `addMonths()` function instead of blindly subtracting 1 month – Learning2Code Jan 17 '19 at 23:43

5 Answers5

0

For substracting in moment.js:

moment().subtract(1, 'months').format("DD-MM-YYYY")

Documentation: http://momentjs.com/docs/#/manipulating/subtract/

Carlos Vieira
  • 559
  • 2
  • 10
  • 22
  • It seems a shame to have to use a whole library for this but I appreciate your reply – Jimmy Jan 17 '19 at 15:33
  • if I may you don't need to reinvent the wheel again... This is an top library with time zones included. Check on git hub the stars – Carlos Vieira Jan 17 '19 at 15:36
  • 1
    If a question doesn't specify using a library, your answer should not be exclusive to one. Instead, answer the question *without* relying a library, and add "But I would suggest using _Library X_ because...". Or, if you don't have an answer without a library, simply suggest using the library *as a comment*. Not to mention, you ignored OP's code entirely, rather than helping them learn by telling them where they went wrong. – Tyler Roper Jan 17 '19 at 15:38
0

You should subtract months by getting the current month, then subtracting the number of months you want and then updating the date variable like this.

function fetchTime() {
  var today = new Date();
  today.setMonth(today.getMonth() - 1);
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  return (today);
}
0

Use the same code, but remove a month. Example:

function fetchTime() {
  var today = new Date();
  today.setMonth(today.getMonth() - 1);
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  return (today);
}
MarcusVinnicius
  • 240
  • 1
  • 7
0

I would separate the formatting from the fetching. You could make your existing formatting function take an optional parameter that defaults to today, so you could call it like you already were for today's date.

 function formatTime(date) {
  var dateToFormat = date || new Date();
  var dd = dateToFormat.getDate();
  var mm = dateToFormat.getMonth() + 1;
  var yyyy = dateToFormat.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }

  return (yyyy + '-' + mm + '-' + dd);
}

Then you could also call it with today's date minus a month or any other date

    formatTime(); //will default to today
    var today = new Date();
    formatTime(addMonths(today,-1)); //format last month's date

As pointed out by RobG in the comments you would need to implement an addMonths function as in Adding months to a Date in JavaScript

function addMonths(date, months) {
  var d = date.getDate();
  date.setMonth(date.getMonth() + +months);
  if (date.getDate() != d) {
    date.setDate(0);
  }
  return date;
}
Learning2Code
  • 521
  • 9
  • 21
  • You can't simply subtract one from the month. E.g for 31 March that will resolve to 31 Feb, which will be adjusted to 3 March or 2 March in leap years. – RobG Jan 17 '19 at 22:54
0

Because your desired format is an ISO 8601 date, you could use JavaScript's .toISOString. You are only concerned with the first 10 characters though (not time), so you'd want to add .substring(0,10).

Date.prototype.toISODateString = function() { return this.toISOString().substring(0,10); }
Date.prototype.addMonths = function(val) { this.setMonth(this.getMonth()+val); return this;}

var date = new Date();
var todayFormatted = date.toISODateString();
console.log(todayFormatted);

var lastMonthFormatted = date.addMonths(-1).toISODateString();
console.log(lastMonthFormatted);            

I've made the formatting steps a function called toISODateString() and added it to the Date prototype, which is a fancy way of saying "You can chain .toISODateString() to any Date now".

To set the date back a month, I've used .setMonth(). I also turned this into a function called addMonths.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • You can't simply add or subtract from the month number, e.g. 31 Jan plus one month will be 2 or 3 March, similarly for 31 March minus one month. – RobG Jan 17 '19 at 22:55
  • 1
    @RobG The behavior you've described is exactly the expected behavior, no? OP has not said anything about accounting for days that don't exist. If you were to ask *"What day was exactly a month ago from March 31?"*, the answer would not be *"February 31"*, so I'm curious as to why you'd expect the code to do that. – Tyler Roper Jan 17 '19 at 22:56
  • I don't think the OP wants 31 Jan plus one month to be 3 March, or for 31 March minus one month to be 3 March. Or 31 July minus one month to be 1 July. Likely they expect a different month, as inferred from "*Can anyone tell me the right way to do this?*" – RobG Jan 17 '19 at 22:58
  • 1
    I guess we disagree then. Personally I find your downvote to be hasty, as it's based on what you personally assume OP wants in that case. Had they specified, I could tidy up my answer. Given that OP has accepted an answer that exhibits the same behavior as mine, I'm more inclined to think that they're alright with it. – Tyler Roper Jan 17 '19 at 22:59
  • @RobG Just stumbled upon [this](https://stackoverflow.com/a/7091965/2026606) completely by chance. Seems you've had this discussion in the past! :) – Tyler Roper Jan 18 '19 at 19:15