I have following message on Login Failed response. The response shows Date in UTC format. I wanted to get the date and convert from UTC to Local. I tried the following but I'm still having the same date formate. Can anyone help me what I'm doing wrong here
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);
On my console print, I'm having same as LoginRes. I was expecting something like :
Too many incorrect attempts. Account is locked until: March 16th 2018, 8:13:14 pm
Your regex doesn't match the date
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);
You can also solve this using 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>
Your regex is incorrect, it does not match the +
before offset, you can use /\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\+\\d{2}:\\d{2}/
instead.
Moreover you can use moment.utc
to parse your input as UTC and local()
to convert it in local mode.
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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.