DEV Community

Discussion on: Two string methods every JavaScript developer should know.

Collapse
 
drinkcsis profile image
drinkcsis • Edited

Interesting...
But how about this?

new Date("2019-08-02T00:00:00.000Z").toLocaleDateString("sq-AL",{ year: 'numeric', month: '2-digit', day: '2-digit' })

Collapse
 
pulges profile image
Oliver Pulges

This method will only work if your javascript environment (browser or server in case of nodejs) is guaranteed to run in UTC. In case of other timezones or daylight saving time shift you can get an error of +-1 days as Date object parses this to local environment time.

Collapse
 
drinkcsis profile image
drinkcsis • Edited

Actually... No.
Date doesn't parse this to local environment time.
That string contains T00:00:00.000Z.It is timezone of date(UTC in current case) . So it will convert correct in every environment!

Thread Thread
 
pulges profile image
Oliver Pulges

Exactly what I was saying, that this is only valid when that timezone containing string is generated in the same environment. I'm living in UTC+2 and parsing the string withe Zulu Z time in the end (set time to 23h to make the point):

new Date("2019-08-02T23:00:00.000Z").toLocaleDateString("sq-AL",{ year: 'numeric', month: '2-digit', day: '2-digit' });

returns 08/03/2019

Thread Thread
 
drinkcsis profile image
drinkcsis

That is way it is good practis to set all servers in utc

Thread Thread
 
pulges profile image
Oliver Pulges • Edited

But you can not guarantee users with their computers to stay put in UTC too. Nobody told the string was parsed in server. If it was though then the split method just calls for SQL injection attack.

Thread Thread
 
danstur profile image
danstur

Also no sane person ever thought "put all your servers in the wrong timezone" was a good idea.

Instead of trying to work around bugs in your code by making every single recorded time in your server wrong, just learn the involved concepts and the available APIs.

Collapse
 
dmratcliffe profile image
Devin Ratcliffe • Edited

This is the answer.

Also, it's strange, because I feel most people know about these string operations.

This is not the situation to use them though, it's mildly ridiculous this was the accepted answer...

To be more clear, the date function can parse more formats of dates then this fix, will the date always have a T? Also the format is decidedly js, which means it probably came from the date function already.