-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.js
More file actions
68 lines (55 loc) · 1.92 KB
/
Copy pathAPI.js
File metadata and controls
68 lines (55 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export async function getTimeOfCity(cityName) {
try {
let response = await fetch("http://worldtimeapi.org/api/timezone");
// Parse the response as JSON
let data = await response.json();
// Find the continent that the city belongs to
let cityInfo = data.find((info) => info.includes(cityName));
// Build the URL for the API request for the city's timezone
let timeUrl = `http://worldtimeapi.org/api/timezone/${cityInfo}`;
// Make the API request for the city's timezone
let timeResponse = await fetch(timeUrl);
// Parse the response as JSON
let timeData = await timeResponse.json();
// Return the current time in the city
return timeData.datetime;
} catch (error) {
// log any errors to the console
console.error("Error fetching data:", error);
alert(
"API fetching time zones & times around the world unavailable! Please refresh the page or try again in a few seconds."
);
return "ERROR FETCHING DATA";
}
}
export async function fetchCities() {
try {
let countries = [];
// fetch the response from the API
let response = await fetch("http://worldtimeapi.org/api/timezone");
let regex = /([^/]*)$/; //regex to filter cities
// parse the response as JSON
let data = await response.json();
// extract the city names from the response data
let cities = data.map(function (item) {
return item.match(regex)[1];
});
cities.forEach(function (city) {
if (
city !== undefined &&
!city.includes("GMT") &&
!city.includes("UTC")
) {
countries.push(city);
}
});
return countries;
} catch (error) {
// log any errors to the console
console.error("Error fetching data:", error);
alert(
"API fetching time zones & times around the world unavailable! Please refresh the page or try again in a few seconds."
);
return "ERROR FETCHING DATA";
}
}