去掉时间字符串的时分秒

发布时间 2023-05-08 16:22:16作者: is橙子

如果您在使用类似于Vue.js的储插值语法,可以通过以下方式来去掉时间字符串中的时分秒:

<view class="info">
  <view class="info_text">活动地点:{{detail.activityAddress }}</view>
  <view class="info_text">活动时间:{{detail.gmtStart | formatDate}}~{{detail.gmtEnd | formatDate}}</view>
  <view class="info_text">活动类型:{{detail.type=="1"?"线上":"线下"}}</view>
</view>

在这里,我们使用了Vue.js的管道符号|,并将detail.gmtStartdetail.gmtEnd传递给名为formatDate的自定义过滤器。接下来,我们可以在Vue.js实例中定义这个过滤器:

方法一:

//过滤时间
        filters: {
            formatDate(date) {
                const nDate = new Date(date)
                const year = nDate.getFullYear()
                const month = nDate.getMonth().toString().padStart(2, 0)
                const day = nDate.getDate().toString().padStart(2, 0)
                return year + '-' + month + '-' + day
            }
        },

方法二:

filters: {
  formatDate: function(value) {
    var date = new Date(value);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
  }
}

在这里,我们将传递给过滤器的时间字符串转换为JavaScript中的Date对象,并使用getFullYear()getMonth()getDate()方法获取年、月和日。最后,我们将这些值连接起来并返回格式化的日期字符串,其中忽略了时分秒。

效果