The other answers have already provided solutions to get the date format, but I think it is worth an explanation about what was the error of your code.
First you extract the value of timestamp using regex, and creates the date. So far so good:
var data = "/Date(1566322265000)/";
var _dtAux = /\/Date\((\d+).*\)\//.exec(data);
var _dtIni = new Date(parseInt(_dtAux[1]));
In this case, the timestamp 1566322265000
corresponds to "August 20, 2019, at 14:31:05, at Brasilia Time". That’s what _dtIni
contains: a date corresponding to this specific instant.
But then you use toLocaleString()
, which returns the date in a specific format (such as a string), and creates another date using this string:
var dtMilissegundos = new Date(_dtIni.toLocaleString());
This is the point that is wrong.
First that, when calling toLocaleString()
no parameters, a format corresponding to the locale which is configured in the browser (which, if I’m not mistaken, depends on the browser’s language settings).
So the first point is that the string that will be generated by this method may not be the same for all customers, since some locales use "day/month/year", others (such as English en-US
) use "month/day/year", others use "year/month/day", etc. And as already explained here, the only standardized format that the Date
recognizes and works the same way in all browsers is the ISO 8601 ("year-month-dayThour:minute:second" - note the letter T
between date and time), and any format other than this may have a different behavior, which varies according to the browser.
For example, in my browser (Chrome, configured with locale pt-BR
- brazilian Portuguese), toLocaleString()
returns the string "20/08/2019 14:31:05"
. And in doing new Date("20/08/2019 14:31:05")
, the result is Invalid Date
(that the snippet below can show how null
). This is because when this format is used, the Chrome implementation assumes that the format is "month/day/year hour:minute:second":
// o Chrome entende que esse formato é mês/dia/ano hora:minuto:segundo
console.log(new Date("11/08/2019 14:31:05")); // 8 de novembro
console.log(new Date("20/08/2019 14:31:05")); // data inválida, pois o mês é 20
And as in the second case, the month is 20, the date is invalid. And when trying to call any method of this invalid date (such as getDate()
, getMonth()
, etc), the result is NaN
.
Probably your browser is configured with a locale which produces a different format than ISO 8601, and which also causes a similar error.
That said, you could have stopped at the creation of _dtIni
. It is already a date corresponding to the timestamp you got with regex (that is, it is already what you need), there is no reason to create another date derived from this. Then just use _dtIni.getDate()
, _dtIni.getMonth()
, etc, to get the right values.
As an alternative to other responses, for this specific format you can use toLocaleString('pt-BR')
:
let data = "/Date(1566322265000)/";
let m = data.match(/\/Date\((\d+)\)\//);
if (m) {
let d = new Date(parseInt(m[1]));
console.log(d.toLocaleString('pt-BR')); // 20/08/2019 14:31:05
}
Note also that I removed the .*
of the regex: the \d+
already takes all the numbers, and then there’s the \)
for closing the parentheses, then .*
will not pick up any character, and makes no difference in this case (it would only do if the original string had more things between the number and closing parentheses).
One detail is that the methods getMonth()
, getDate()
, etc, and the very toLocaleString()
return the numerical values of the date taking into account the browser’s time zone (which in turn, usually uses what is configured in the operating system). This can be changed by passing Timezone as parameter:
let data = "/Date(1566322265000)/";
let m = data.match(/\/Date\((\d+)\)\//);
if (m) {
let d = new Date(parseInt(m[1]));
console.log(d.toLocaleString('pt-BR', { timeZone: 'UTC' })); // 20/08/2019 17:31:05
console.log(d.toLocaleString('pt-BR', { timeZone: 'America/Sao_Paulo' })); // 20/08/2019 14:31:05
console.log(d.toLocaleString('pt-BR', { timeZone: 'Asia/Tokyo' })); // 21/08/2019 02:31:05
}
Note that both the day and time can change according to the chosen time zone.
Already using the getters, cannot convert to any Timezone. It is only possible to get the corresponding values in UTC using the methods getUTCMonth()
, getUTCDate()
, etc..
Another detail is that the documentation of toLocaleString
says the following:
Most of the time, the formatting returned by toLocaleString()
is consistent. However, this Might change in the Future and isn’t Guaranteed for all Languages - output Variations are by design and allowed by the Specification. Most notably, the IE and Edge browsers Insert bidirectional control characters Around Dates, so the output text will flow properly when Concatenated with other text.
In free translation (emphasis mine):
Most of the time, the format returned is toLocaleString()
is consistent. However, it can change in the future and is not guaranteed for all languages - variations in the result are allowed by the specification. The most notable are the IE and Edge browsers, which insert bidirectional control characters around dates, so the text can follow the correct flow when concatenated with another text.
In this answer there’s also a quote about:
... browsers are allowed a large amount of leeway with what formats they support and what characters Compose the format.
... you cannot expect to be Able to compare the Results of toLocaleString
Across browsers or Even expect the same browser to continue Giving the same result from release to release.
In free translation:
... browsers are allowed a wide range of formats supported and which characters can compose the format.
... you cannot expect the comparison of the results of toLocaleString
between different browsers work, or that the same browser keeps giving the same results from one version to another.
That is, there is no guarantee that toLocaleString()
always return the same format 100% of the time (although many locales are apparently stable in this sense). So if you always want the same format, regardless of the settings of the locale or browser, prefer the reply from Luiz Felipe.
Things like
new Date("xxxx").getMonth()
produceNaN
as a result. Therefore, what is in your variableresponse.listarLoginLogout
, especially in the fieldDATA
thereof?– Victor Stafusa
Use
/\/Date\((\d+).*\)\//.exec(data)
does not seem a good idea from a security point of view.– Victor Stafusa
Nan/Nan/Nan Nan:Nan:Nan batmaaaan
– Woss
@Andersoncarloswoss Whenever I see a lot of Nan I remember this: https://www.destroyallsoftware.com/talks/wat
– hkotsubo
Good morning! Thanks @Victor Stafusa for the comments I solved the problem as suggested below and I will mark as answered post, however answering your question within the field
DATA
has the following string:"/Date(1566322265000)/"
.– hard123