微信小程序wxs实现UTC转北京时间

微信小程序实现UTC转北京时间

打脸一刻:最近在迭代原生微信小程序,好一段时间没写原生的,有点不习惯;

咦,更新数据咋不生效呢?原来还停留在 this.xxx;

哟,事件又没反应了?传参咋报错了。。。,别做梦啦!传参用 data-xxx;


UTC 转 北京时间

  • wxs不支持使用 JS 全局对象和函数,例 new Date()等;
  • 可以使用 wxs 内置的一些简单函数和操作;
  • UTC 时间 与 北京时间相差 8小时;

var formatNumber = function(n) {
	n = n.toString()
	return n[1] ? n : '0' + n
}

var utcToBeijingTime = function(time, type = 'date') {
	if (!time || arguments.length === 0) return '';
	var date;

	time = time.replace("Z", " ").replace(getRegExp('-', 'g'), "/");
	var ts = time.split('T');
	var t1 = ts[0];
	var t2 = ts[1].split('.')[0];
	time = t1 + " " + t2;
	time = getDate(time).getTime() + 8 * 3600000;
	date = getDate(time);

	var y = date.getFullYear();
	var m = formatNumber(date.getMonth() + 1);
	var d = formatNumber(date.getDate());
	var h = formatNumber(date.getHours());
	var M = formatNumber(date.getMinutes());
	var s = formatNumber(date.getSeconds());

	var formatStr = y + '-' + m + '-' + d;
	if (type == 'datetime') return formatStr += ' ' + h + ':' + M + ':' + s;

	return formatStr
}


module.exports = {
    utcToBJTime: utcToBeijingTime
}

使用

<wxs src="../../utils/filter.wxs" module="filter" />
 
<view>{{ filter.utcToBJTime(currentDate) }}</view>

你可能感兴趣的:(微信小程序,微信小程序,微信小程序UTC转北京时间)