我在Login Failed响应中有以下消息。响应以UTC格式显示日期。我想获取日期并从UTC转换为本地。 我试过以下但我仍然有相同的日期格式。任何人都可以帮助我,我在这里做错了什么
var loginRes = 'Too many incorrect attempts. Account is locked until: 2018-03-16T05:13:58+00:00'
var dateRegx = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}-\d{2}:\d{2}/;
var ErrorMessage = (loginRes).replace(dateRegx,
function(match){
return moment(match).format("MMMM Do YYYY, h:mm:ss a");
});
console.log(ErrorMessage);
在我的控制台打印件上,我和LoginRes一样。我期待的是:
Too many incorrect attempts. Account is locked until: March 16th 2018, 8:13:14 pm
答案 0 :(得分:1)
您的正则表达式与日期
不匹配var loginRes = 'Too many incorrect attempts. Account is locked until: 2018-03-16T05:13:58+00:00'
var dateRegx = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/;
var ErrorMessage = (loginRes).replace(dateRegx,
function(match){
console.log('tst')
return moment(match).format("MMMM Do YYYY, h:mm:ss a");
});
console.log(ErrorMessage);
答案 1 :(得分:1)
您也可以使用lastIndexOf()
解决此问题:
var loginRes = 'Too many incorrect attempts. Account is locked until: 2018-03-16T05:13:58+00:00';
var idx = loginRes.lastIndexOf(' ');
var ErrorMessage = loginRes.substring(0, idx) + ' ' +
moment(loginRes.substring(idx)).format("MMMM Do YYYY, h:mm:ss a");
console.log(ErrorMessage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
答案 2 :(得分:1)
您的正则表达式不正确,与偏移前的+
不匹配,您可以使用/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}/
代替。
此外,您可以使用moment.utc
将输入解析为UTC,并使用local()
将其转换为本地模式。
var loginRes = 'Too many incorrect attempts. Account is locked until: 2018-03-16T05:13:58+00:00'
var dateRegx = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}/;
var ErrorMessage = (loginRes).replace(dateRegx,
function(match){
return moment.utc(match).local().format("MMMM Do YYYY, h:mm:ss a");
});
console.log(ErrorMessage);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
&#13;