• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
淡然离场
博客园    首页    新随笔    联系   管理    订阅  订阅

uniapp获取当前日期时间

这里使用的是封装式写法,使用时需要用到import引入

1.common/getdateTime.js

```javascript
/**
* @param {String} str (y-m-d h:i:s) y:年 m:月 d:日 h:时 i:分 s:秒
*/
function dateTimeStr(str){
var date = new Date(),
year = date.getFullYear(), //年
month = date.getMonth() + 1, //月
day = date.getDate(), //日
hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //时
minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(), //分
second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); //秒
month >= 1 && month <= 9 ? (month = "0" + month) : "";
day >= 0 && day <= 9 ? (day = "0" + day) : "";
hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
second >= 0 && second <= 9 ? (second = "0" + second) : "";
if(str.indexOf('y') != -1){
str = str.replace('y', year)
}
if(str.indexOf('m') != -1){
str = str.replace('m', month)
}
if(str.indexOf('d') != -1){
str = str.replace('d', day)
}
if(str.indexOf('h') != -1){
str = str.replace('h', hour)
}
if(str.indexOf('i') != -1){
str = str.replace('i', minute)
}
if(str.indexOf('s') != -1){
str = str.replace('s', second)
}
return str;
}

module.exports = {
dateTimeStr: dateTimeStr,
}
```

### 需要调用的页面 pages/index/index

```javascript
<script>
import getDateTime from '@/common/getdateTime.js';
export default {
data() {
return {
nowTime: '',

}
},
onLoad(option) {
var timeStr = getDateTime.dateTimeStr('y-m-d h:i:s'); // y:年 m:月 d:日 h:时 i:分 s:秒 中间的分割符号可更改
this.nowTime = timeStr
},
methods: {

}
}
</script>

 

```

posted @ 2021-06-25 20:58  淡然离场  阅读(7179)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3