函数计算,云函数获取当前时间,和北京时间差了9个小时,怎么解决 ?
函数计算默认是UTC时间,可以配置环境变量进行修改。
可以配置环境变量进行时区修改:TZ = Asia/Shanghai 如何配置环境变量
需要注意的是,在nodejs环境中,console.log(date) 会转成utc 时间,可以直接先转成 string , 然后在console.log,
var date = new Date();console.info(date.toTimeString());或者自己重写 console.log, 如下面代码所示'use strict';var util = require('util');function _writeToStdout(level, msg) {const now = new Date();// 自定义格式const timeStr = $now.getFullYear()-$now.getMonth()+1-$now.getDate()T$now.getHours():$now.getMinutes():$(now.getSeconds()*1000+now.getMilliseconds())/1000Z// const timeStr = now.toLocaleString();let requestID = process._fc && process._fc.requestId ? process._fc.requestId : '';let logMsg = $timeStr $requestID [$level] $msg;logMsg = logMsg.replace(/\n/g, '\r');process.stdout.write(logMsg + '\n');}var log = function (level, msg, ...params) {var logMsg = util.format(msg, ...params);_writeToStdout(level, logMsg);};console.log = function (msg, ...params) {log('verbose', msg, ...params);};console.info = function (msg, ...params) {log('info', msg, ...params);};console.warn = function (msg, ...params) {log('warn', msg, ...params);};console.error = function (msg, ...params) {log('error', msg, ...params);};console.debug = function (msg, ...params) {log('debug', msg, ...params);};exports.handler = (event, context, callback) => {// const eventObj = JSON.parse(event.toString());console.log('hello world');callback(null, 'hello world');}
此答案来自钉钉群“阿里函数计算官网客户”
赞0
踩0