function getToday() { var app = getApp() var servertime = app.globalData.servertime return servertime }怎么使用上面的函数替换下面的函数function getToday() { var date = getDate() var y = date.getFullYear() var m = date.getMonth() + 1 var d = date.getDate() return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + '' }
时间: 2023-12-03 19:46:38 浏览: 28
您可以将下面的函数替换为上面的函数,如下所示:
```
function getToday() {
var app = getApp();
var servertime = app.globalData.servertime;
var date = new Date(servertime);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + '';
}
```
这个新的 `getToday()` 函数将获取全局变量中的服务器时间,然后转换为本地时间并返回格式化的日期字符串。注意,由于在此函数中使用了 `getApp()`,因此必须确保在调用此函数之前,已经创建了 App 实例。
相关问题
async function getToday() { console.log('获取服务器时间') if (app.globalData.servertime) { return app.globalData.servertime; } else { let res = await wx.cloud.callFunction({name: 'getServerTime'}); app.globalData.servertime = res.result; return app.globalData.servertime; } }怎么给这个函数增加失效时间,超过10分钟后就会重新从服务器获取时间
你可以通过在函数中保存上一次获取时间的时间戳,然后在下一次获取时间时与当前时间戳比较,如果超过了设定的失效时间,就重新从服务器获取。具体实现可以参考下面的代码:
```
async function getToday() {
console.log('获取服务器时间');
const now = Date.now();
const cacheTime = app.globalData.servertimeTime || 0;
const cacheData = app.globalData.servertime || null;
if (cacheData && now - cacheTime < 10 * 60 * 1000) {
// 数据未过期,直接返回缓存数据
return cacheData;
} else {
// 数据已过期或首次获取,重新从服务器获取数据
const res = await wx.cloud.callFunction({name: 'getServerTime'});
app.globalData.servertime = res.result;
app.globalData.servertimeTime = now;
return app.globalData.servertime;
}
}
```
在上面的代码中,我们首先获取当前时间戳 `now`,然后获取缓存的时间戳 `cacheTime` 和缓存的数据 `cacheData`。如果缓存数据未过期,则直接返回缓存数据;否则,重新从服务器获取数据,并更新缓存时间戳和缓存数据。其中,失效时间设为 10 分钟,即 10 * 60 * 1000 毫秒。
async function getUsersinternet(openid) { if (app.globalData.usersinternets) return app.globalData.usersinternets else{ let res = await wx.cloud.callFunction({ name: 'getUsersinternet', data: { usersID: openid, today: lib.getToday() } }) return app.globalData.usersinternets = res.result } }指出这段代码中的问题,并把正确的代码发给我
这段代码中存在一个问题,即无论是否已经获取了 `app.globalData.usersinternets`,都会执行异步请求获取数据。正确的代码应该是:
```javascript
async function getUsersinternet(openid) {
if (app.globalData.usersinternets) {
return app.globalData.usersinternets;
} else {
let res = await wx.cloud.callFunction({
name: 'getUsersinternet',
data: {
usersID: openid,
today: lib.getToday()
}
});
app.globalData.usersinternets = res.result;
return app.globalData.usersinternets;
}
}
```
在这个正确的版本中,如果 `app.globalData.usersinternets` 已经存在,则直接返回该值;否则,执行异步请求获取数据,并将结果存储到 `app.globalData.usersinternets` 中后再返回该值。