小程序 获取当前时间的前五天

这篇博客记录了在JavaScript中如何获取当前时间并计算出前五天的方法,适用于小程序开发。示例代码展示了在页面onShow或onLoad钩子中调用相应函数来实现时间循环展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在前:记录一下js 中获取时间的方式,和其转化过程


<view class="intro">
  <block wx:for="{{timearr}}" wx:key="index">
    <text>{{item.time}}</text>
  </block>
</view>

在页面中循环出时间,如上


.intro {
  font-size: 16px;
  color: #333;
  margin: 30px;
  text-align: center;
}

.intro text {
  display: block
}

一些样式,当然这只是一个小的demo


const app = getApp()

Page({
  data: {
    timearr:[],
  },
  onShow: function () {
    this.dadtaTap()
  },
  // 时间处理
  timehandTap: function (symbol, n) {
    symbol = symbol || '.';
    let date = new Date();
    date = date.setDate(date.getDate() + n);
    date = new Date(date)
    let year = date.getFullYear();
    let month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return year + symbol + month + symbol + day;
  },
  // 数据处理
  dadtaTap: function () {
    let that = this;
    for (let i = 0; i < 5; i++) {
      console.log(-(i + 1))
      let times = this.timehandTap(".", -(i + 1));
      // console.log(times)
      let time = "timearr[" + i + "].time"; //此处的数组的属性可当做是新添加的键
      // console.log(time)
      that.setData({
        [time]: times
      })
    }
  },
})

当然,此例中在onShow的钩子函数中调用方法,也可以在onLoad中调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值