在JavaScript中为当前Unix时间戳添加一个月

8yoxcaq7  于 2023-06-28  发布在  Java
关注(0)|答案(3)|浏览(99)

我有这个时间戳1688452200

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

我想添加1个月到这个时间戳,但这是行不通的

zujrkrfu

zujrkrfu1#

你需要一些东西在这里:

  • UNIX时间戳采用UTC格式,因此我们需要向其添加时区偏移量
  • 将得到的UNIX时间戳转换为JS时间戳(乘以毫秒)。
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>
zi8p0yeb

zi8p0yeb2#

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

gcxthw6b3#

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())

相关问题