-1

I have From-Date, To-Date, and Total-Days...if i have a From-Date and Total-Days then i have to calculate To-Date automatically I Used The Following method to get the To-Date day

var FromDate = $("#FromDate").val(); var TotalDays = $("#txtDays").val(); FromDate.setDate(parseInt(FromDate.getDate()) + parseInt(NoOfDays)); var dd = FromDate.getDate()-1;

This Will Not Work For Day 1 of every month.....Since It Returns 0 How To Handle This Situation or help me to solve this in another way....Thanx In Advance

  • what exactly are you trying to achieve, then maybe it will be easier for us to help you out better – warl0ck Aug 29 '18 at 06:10
  • 1
    Not related to your question, but it is a very bad idea to reassign variables holding built-ins. After you run `Date = ...`, you lose access to the `Date` constructor. – Amadan Aug 29 '18 at 06:10
  • I think he's trying to get 08-19-2018 in this case – NoobTW Aug 29 '18 at 06:11
  • 2
    `var Date=new Date` think what this does! You are overwriting the `Date` object with an instance of Date - will cause issues ... look into d.setDate ... hint, it doesn't matter if you set the date to 0, Date object is smart – Jaromanda X Aug 29 '18 at 06:11

2 Answers2

2

try this

var d = new Date('08-20-2018');
d.setDate(d.getDate() - 1);
alert(d.getDate());

Date object is smart enough to know what to do if you set any of the "components" (month, day, hour, minute, second, millisecond) outside of "normal" range - it does the maths for you

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

If you only need to know the previous date, you can always subtract the 24hours from the epoch time and then convert it back to date object and get the date like:

new Date(new Date('08-01-2018').getTime() - 24*3600000).getDate()

  1. new Date('08-01-2018').getTime() will give you the epoch time of the date you want previous date from

  2. 24*3600000 is subtracting the 24 milliseconds from the epoch

  3. After subtracting the value you get the previous day epoch and using the new Date() constructor you are getting the Date object again

  4. On this new date object you can call getDate() method to get the correct result of 31.

I have given date to Date constructor in MM-DD-YYYY format

warl0ck
  • 3,356
  • 4
  • 27
  • 57