Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Created June 15, 2023 14:06
Show Gist options
  • Save HallexCosta/47bdb2e55d074b601ec080f3880d4668 to your computer and use it in GitHub Desktop.
Save HallexCosta/47bdb2e55d074b601ec080f3880d4668 to your computer and use it in GitHub Desktop.
Simulando conflito entre timezones do EUA e BRASIL atráves de ordenação por data
const items = []
// simulate request add item using api
function api(id, date, country) {
const item = {
id,
date,
timestamp: Date.parse(date), // timestamp
country
}
items.push(item)
}
// configure timezone to EUA
const eua = new Intl.DateTimeFormat('en-US', {
timeZone: 'Europe/Amsterdam',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
api(1, eua.format(new Date()), 'eua') // add item 1 from eua
api(2, eua.format(new Date()), 'eua') // add item 2 from eua
// configure timezone to Brazil
const brazil = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/Sao_Paulo',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
api(3, brazil.format(new Date()), 'brazil') // add item 3 from brazil
// sort item by nearest date
const itemsSortBy = items.sort((a, b) => {
return (a.timestamp) - (b.timestamp)
})
for (const item of itemsSortBy) {
console.log(item)
}
/*
OUTPUT:
{
id: 3,
date: '06/15/2023, 10:57:42 AM',
timestamp: 1686837462000,
country: 'brazil'
}
{
id: 1,
date: '06/15/2023, 03:57:42 PM',
timestamp: 1686855462000,
country: 'eua'
}
{
id: 2,
date: '06/15/2023, 03:57:42 PM',
timestamp: 1686855462000,
country: 'eua'
}
*/
const items = []
// simulate request add item using api
function api(id, date, country) {
const item = {
id,
date: (new Date(date)).toLocaleString('en-US'),
timestamp: date, // timestamp
country
}
items.push(item)
}
// configure timezone to EUA
const eua = new Intl.DateTimeFormat('en-US', {
timeZone: 'Europe/Amsterdam',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
api(1, Date.now(), 'eua') // add item 1 from eua
api(2, Date.now(), 'eua') // add item 2 from eua
// configure timezone to Brazil
const brazil = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/Sao_Paulo',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
api(3, Date.now(), 'brazil') // add item 3 from brazil
// sort item by nearest date
const itemsSortBy = items.sort((a, b) => (a.timestamp) - (b.timestamp))
for (const item of itemsSortBy) {
console.log(item)
}
/*
OUTPUT:
{
id: 1,
date: '6/15/2023, 11:04:51 AM',
timestamp: 1686837891470,
country: 'eua'
}
{
id: 2,
date: '6/15/2023, 11:04:51 AM',
timestamp: 1686837891471,
country: 'eua'
}
{
id: 3,
date: '6/15/2023, 11:04:51 AM',
timestamp: 1686837891471,
country: 'brazil'
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment