0

I have this timestamp 1688452200

const startdate = new Date('1688452200')
const newstartDate = new Date(startdate.setMonth(startdate.getMonth() + 1));
console.log('newDate:', newstartDate);
const newStartDateTime = newstartDate.getTime();

want to add 1 month to this timestamp but this is not working

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
user3653474
  • 3,393
  • 6
  • 49
  • 135
  • You're passing a string, so it will be parsed looking for year, month, day, etc. If you want the value to be treated as a time value (millisecond offset since the epoch), it must be a number. See Alexander Nenashev's answer (which converts to number and milliseconds at the same time). – RobG Jun 26 '23 at 13:18
  • Note there are foibles to overcome when incrementing a date by a month, see [*JavaScript function to add X months to a date*](https://stackoverflow.com/questions/2706125/javascript-function-to-add-x-months-to-a-date). – RobG Jun 26 '23 at 13:19

3 Answers3

2

You need a few things here:

  • a UNIX timestamp is in the UTC so we need to add the timezone offset to it
  • convert the resulting UNIX timestamp to the JS timestamp (multiply by milliseconds).

const startdate = new Date((unixTimestamp - new Date().getTimezoneOffset() * 60) * 1000);
console.log('startdate:', startdate);
startdate.setMonth(startdate.getMonth() + 1);
console.log('newDate:', startdate);
<script>
  const unixTimestamp = (new Date(2023,4,31).getTime() / 1000).toString();
</script>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
0
const oneMonthToUnixTimestamp = () => {  
    let date = new Date();  
    const month = date.getMonth() + 1;  
    let year = date.getYear();  
    const epoch =  date.valueOf();  
    let dayToHr = 24;  
    const hrToMin = 60;  
    const minToSec = 60;  
    const secToMill = 1000;  
    let numberofdate = new Date(year, month, 0).getDate(); 
    let addedmillisec = numberofdate * dayToHr * hrToMin * minToSec * secToMill;   
    return epoch + addedmillisec  
}

console.log(oneMonthToUnixTimestamp())
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Albert Einstein Jun 28 '23 at 08:49
-1
const startdate = new Date(1688452200*1000);
const newstartDate = new Date(startdate.setMonth(startdate.getMonth() + 1));
console.log('newDate:', newstartDate);
const newStartDateTime = newstartDate.getTime();