The Search Country by Time Zone endpoint allows you to find all countries that use a specific timezone. This is essential for scheduling applications, international business tools, and time-sensitive features.
All API requests require authentication using an API key passed as a query parameter.
https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC+01:00
https://api.countrydataapi.com/v1/countries/timezone
Returns a list of all countries according to a timezone
There are 4 types of operations:
BASIC: Returns the fields id, lang, country_name, country_short_iso, country_phone_code, country_cca2, country_ccn3, country_cca3, country_cioc.
NORMAL: Returns the previous fields and adds country_independent, country_status, country_unMember, country_flag, country_map_googleMaps, country_map_openStreetMaps, country_fifa, country_flag_png, country_flag_svg, country_flag_alt, country_coatOfArms_png, country_coatOfArms_svg, country_startofWeek, country_continent_code, country_current_currency, country_GDP, country_location, country_land, country_terrain, country_climate, country_natural_hazards, country_note, country_history, country_GDP_per_capita_PPP, country_life_expectancy, country_median_age, country_birth_rate, country_death_rate, country_sex_ratio, country_literacy, country_roadways, country_airports, country_railways, country_waterways, country_heliports, country_airports_paved, country_wikipedia_url.
ADVANCED: Returns the previous fields and adds country_car_info, _country_idd_info.
ALL: Returns the previous fields and adds country_tld, country_capital, country_altSpellings, country_latLng, country_borders, country_timezones, country_continents, country_currencies, country_languages, country_translations, country_capital_info, country_demonyms, country_name.nativeName.
Each country returned with the BASIC method will cost 1 tokens.
Each country returned with the NORMAL method will cost 2 tokens.
Each country returned with the ADVANCED method will cost 3 tokens.
Each country returned with the ALL method will cost 4 tokens.
| Parameter | Type | Description |
|---|---|---|
| apikey | required, token | Authentication key of the account |
| timezone | required, string | Time zone you want to search for. E.g., "UTC+01:00" |
| limitToken | optional, number | 1000 (default). Maximum number of countries to be returned |
| lang | optional, lang | en (default). Expected language of the response |
| fields | optional, string | id,lang,country_name (default). Expected fields in the response |
[
{
"id": "33be30c5-80fc-429d-bf10-bd11f2e3e84c",
"lang": "en",
"country_name": "Albania",
"country_short_iso": "AL",
"country_phone_code": "355",
"country_cca2": "AL",
"country_ccn3": "008",
"country_cca3": "ALB",
"country_cioc": "ALB",
"country_independent": true,
"country_status": "officially-assigned",
"country_unMember": true,
"country_capital": ["Tirana"],
"country_region": "Europe",
"country_subregion": "Southeast Europe",
"country_flag": "flag-emoji",
"country_timezones": ["UTC+01:00"],
"country_flag_png": "https://flagcdn.com/w320/al.png",
"country_flag_svg": "https://flagcdn.com/al.svg"
},
{
"id": "another-country-id",
"lang": "en",
"country_name": "Germany",
"country_short_iso": "DE",
"country_phone_code": "49",
"country_cca2": "DE",
"country_ccn3": "276",
"country_cca3": "DEU",
"country_cioc": "GER",
"country_timezones": ["UTC+01:00"],
"country_flag_png": "https://flagcdn.com/w320/de.png"
}
]
# Search countries by timezone
curl -X GET "https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC%2B01:00"
# Note: URL encode the + sign as %2B
curl -X GET "https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC%2B05:30"
# With specific fields
curl -X GET "https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC%2B00:00&fields=id,lang,country_name,country_flag_png,country_capital"
# UTC timezone (no offset)
curl -X GET "https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC"
# Negative offset timezone
curl -X GET "https://api.countrydataapi.com/v1/countries/timezone?apikey=YOUR_API_KEY&timezone=UTC-05:00"
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://api.countrydataapi.com/v1/countries';
// Search countries by timezone
async function searchCountriesByTimezone(timezone, options = {}) {
const params = new URLSearchParams({
apikey: API_KEY,
timezone: timezone,
...options
});
try {
const response = await fetch(`${BASE_URL}/timezone?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error searching countries by timezone:', error);
throw error;
}
}
// Usage examples
// Central European Time
searchCountriesByTimezone('UTC+01:00')
.then(countries => {
console.log('Countries in UTC+01:00:', countries.length);
countries.forEach(c => console.log(` - ${c.country_name}`));
});
// India Standard Time
searchCountriesByTimezone('UTC+05:30', {
fields: 'id,lang,country_name,country_flag_png,country_capital'
})
.then(countries => {
console.log('Countries in IST:', countries);
});
// Eastern Standard Time (US)
searchCountriesByTimezone('UTC-05:00')
.then(countries => {
console.log('Countries in EST:', countries);
});
// Get all timezones for a specific use case
async function getTimezoneCountryCount() {
const commonTimezones = [
'UTC-08:00', 'UTC-05:00', 'UTC+00:00',
'UTC+01:00', 'UTC+05:30', 'UTC+08:00'
];
for (const tz of commonTimezones) {
const countries = await searchCountriesByTimezone(tz);
console.log(`${tz}: ${countries.length} countries`);
}
}
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.countrydataapi.com/v1/countries',
params: {
apikey: 'YOUR_API_KEY'
}
});
// Search countries by timezone
async function searchCountriesByTimezone(timezone, options = {}) {
try {
const response = await apiClient.get('/timezone', {
params: {
timezone: timezone,
...options
}
});
return response.data;
} catch (error) {
if (error.response) {
console.error('API Error:', error.response.status, error.response.data);
} else {
console.error('Network Error:', error.message);
}
throw error;
}
}
// Timezone service for scheduling applications
const timezoneService = {
async getCountriesInTimezone(timezone) {
return searchCountriesByTimezone(timezone, {
fields: 'id,lang,country_name,country_flag_png,country_capital,country_timezones'
});
},
async getTimezoneDetails(timezone) {
const countries = await this.getCountriesInTimezone(timezone);
return {
timezone,
countryCount: countries.length,
countries: countries.map(c => ({
name: c.country_name,
flag: c.country_flag_png,
capital: c.country_capital
}))
};
},
// Common timezone presets
async getEuropeanCountries() {
const timezones = ['UTC+00:00', 'UTC+01:00', 'UTC+02:00', 'UTC+03:00'];
const results = [];
for (const tz of timezones) {
const countries = await this.getCountriesInTimezone(tz);
results.push(...countries);
}
// Remove duplicates
return [...new Map(results.map(c => [c.id, c])).values()];
}
};
// Usage
timezoneService.getTimezoneDetails('UTC+01:00')
.then(details => {
console.log(`${details.countryCount} countries in ${details.timezone}`);
});
import { useState, useCallback, useMemo } from 'react';
const API_KEY = 'YOUR_API_KEY';
// Common timezones for selector
const COMMON_TIMEZONES = [
{ value: 'UTC-12:00', label: 'UTC-12:00 (Baker Island)' },
{ value: 'UTC-08:00', label: 'UTC-08:00 (Pacific Time)' },
{ value: 'UTC-05:00', label: 'UTC-05:00 (Eastern Time)' },
{ value: 'UTC-03:00', label: 'UTC-03:00 (Brazil)' },
{ value: 'UTC+00:00', label: 'UTC+00:00 (GMT)' },
{ value: 'UTC+01:00', label: 'UTC+01:00 (Central European)' },
{ value: 'UTC+02:00', label: 'UTC+02:00 (Eastern European)' },
{ value: 'UTC+03:00', label: 'UTC+03:00 (Moscow)' },
{ value: 'UTC+05:30', label: 'UTC+05:30 (India)' },
{ value: 'UTC+08:00', label: 'UTC+08:00 (China/Singapore)' },
{ value: 'UTC+09:00', label: 'UTC+09:00 (Japan/Korea)' },
{ value: 'UTC+10:00', label: 'UTC+10:00 (Australia Eastern)' },
{ value: 'UTC+12:00', label: 'UTC+12:00 (New Zealand)' }
];
function useTimezoneSearch() {
const [countries, setCountries] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const searchByTimezone = useCallback(async (timezone) => {
if (!timezone) {
setCountries([]);
return;
}
setLoading(true);
setError(null);
const params = new URLSearchParams({
apikey: API_KEY,
timezone: timezone,
fields: 'id,lang,country_name,country_flag_png,country_capital,country_region,country_timezones'
});
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/countries/timezone?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setCountries(data);
} catch (err) {
setError(err.message);
setCountries([]);
} finally {
setLoading(false);
}
}, []);
return { countries, loading, error, searchByTimezone };
}
function TimezoneSearchComponent() {
const [selectedTimezone, setSelectedTimezone] = useState('');
const { countries, loading, error, searchByTimezone } = useTimezoneSearch();
const handleTimezoneChange = (e) => {
const timezone = e.target.value;
setSelectedTimezone(timezone);
if (timezone) {
searchByTimezone(timezone);
}
};
const groupedByRegion = useMemo(() => {
return countries.reduce((acc, country) => {
const region = country.country_region || 'Other';
if (!acc[region]) acc[region] = [];
acc[region].push(country);
return acc;
}, {});
}, [countries]);
return (
<div className="timezone-search-container">
<h2>Find Countries by Time Zone</h2>
<div className="timezone-selector">
<label htmlFor="timezone-select">Select a timezone:</label>
<select
id="timezone-select"
value={selectedTimezone}
onChange={handleTimezoneChange}
className="timezone-select"
>
<option value="">-- Select Timezone --</option>
{COMMON_TIMEZONES.map((tz) => (
<option key={tz.value} value={tz.value}>
{tz.label}
</option>
))}
</select>
</div>
{loading && <div className="loading">Loading countries...</div>}
{error && (
<div className="error-message">
Error: {error}
</div>
)}
{countries.length > 0 && (
<div className="results">
<h3>
{countries.length} countries in {selectedTimezone}
</h3>
{Object.entries(groupedByRegion).map(([region, regionCountries]) => (
<div key={region} className="region-group">
<h4>{region} ({regionCountries.length})</h4>
<div className="country-grid">
{regionCountries.map((country) => (
<div key={country.id} className="country-card">
<img
src={country.country_flag_png}
alt={`${country.country_name} flag`}
className="country-flag"
/>
<div className="country-info">
<strong>{country.country_name}</strong>
<span>{country.country_capital?.join(', ')}</span>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
);
}
export default TimezoneSearchComponent;
<template>
<div class="timezone-search">
<h2>Find Countries by Time Zone</h2>
<div class="timezone-selector">
<label for="timezone-select">Select a timezone:</label>
<select
id="timezone-select"
v-model="selectedTimezone"
@change="handleTimezoneChange"
class="timezone-select"
>
<option value="">-- Select Timezone --</option>
<option
v-for="tz in commonTimezones"
:key="tz.value"
:value="tz.value"
>
{{ tz.label }}
</option>
</select>
</div>
<div v-if="loading" class="loading">Loading countries...</div>
<div v-if="error" class="error-message">{{ error }}</div>
<div v-if="countries.length > 0" class="results">
<h3>{{ countries.length }} countries in {{ selectedTimezone }}</h3>
<div
v-for="(regionCountries, region) in groupedByRegion"
:key="region"
class="region-group"
>
<h4>{{ region }} ({{ regionCountries.length }})</h4>
<div class="country-grid">
<div
v-for="country in regionCountries"
:key="country.id"
class="country-card"
>
<img
:src="country.country_flag_png"
:alt="`${country.country_name} flag`"
class="country-flag"
/>
<div class="country-info">
<strong>{{ country.country_name }}</strong>
<span>{{ formatCapital(country.country_capital) }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const API_KEY = 'YOUR_API_KEY';
const commonTimezones = [
{ value: 'UTC-12:00', label: 'UTC-12:00 (Baker Island)' },
{ value: 'UTC-08:00', label: 'UTC-08:00 (Pacific Time)' },
{ value: 'UTC-05:00', label: 'UTC-05:00 (Eastern Time)' },
{ value: 'UTC-03:00', label: 'UTC-03:00 (Brazil)' },
{ value: 'UTC+00:00', label: 'UTC+00:00 (GMT)' },
{ value: 'UTC+01:00', label: 'UTC+01:00 (Central European)' },
{ value: 'UTC+02:00', label: 'UTC+02:00 (Eastern European)' },
{ value: 'UTC+03:00', label: 'UTC+03:00 (Moscow)' },
{ value: 'UTC+05:30', label: 'UTC+05:30 (India)' },
{ value: 'UTC+08:00', label: 'UTC+08:00 (China/Singapore)' },
{ value: 'UTC+09:00', label: 'UTC+09:00 (Japan/Korea)' },
{ value: 'UTC+10:00', label: 'UTC+10:00 (Australia Eastern)' },
{ value: 'UTC+12:00', label: 'UTC+12:00 (New Zealand)' }
];
const selectedTimezone = ref('');
const countries = ref([]);
const loading = ref(false);
const error = ref(null);
const groupedByRegion = computed(() => {
return countries.value.reduce((acc, country) => {
const region = country.country_region || 'Other';
if (!acc[region]) acc[region] = [];
acc[region].push(country);
return acc;
}, {});
});
const formatCapital = (capital) => {
return capital?.join(', ') || 'N/A';
};
const handleTimezoneChange = async () => {
if (!selectedTimezone.value) {
countries.value = [];
return;
}
loading.value = true;
error.value = null;
const params = new URLSearchParams({
apikey: API_KEY,
timezone: selectedTimezone.value,
fields: 'id,lang,country_name,country_flag_png,country_capital,country_region,country_timezones'
});
try {
const response = await fetch(
`https://api.countrydataapi.com/v1/countries/timezone?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
countries.value = await response.json();
} catch (err) {
error.value = err.message;
countries.value = [];
} finally {
loading.value = false;
}
};
</script>
<style scoped>
.timezone-search {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.timezone-selector {
margin-bottom: 20px;
}
.timezone-select {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
margin-top: 5px;
}
.region-group {
margin-bottom: 20px;
}
.region-group h4 {
border-bottom: 2px solid #4CAF50;
padding-bottom: 5px;
}
.country-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
}
.country-card {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border: 1px solid #eee;
border-radius: 8px;
}
.country-flag {
width: 40px;
height: auto;
border-radius: 2px;
}
.country-info {
display: flex;
flex-direction: column;
}
.country-info span {
font-size: 0.85em;
color: #666;
}
.loading {
text-align: center;
padding: 20px;
color: #666;
}
.error-message {
color: #dc3545;
padding: 10px;
background-color: #f8d7da;
border-radius: 4px;
}
</style>
// timezone-search.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
export interface Country {
id: string;
lang: string;
country_name: string;
country_flag_png?: string;
country_capital?: string[];
country_region?: string;
country_timezones?: string[];
}
export interface TimezoneOption {
value: string;
label: string;
}
@Injectable({
providedIn: 'root'
})
export class TimezoneSearchService {
private http = inject(HttpClient);
private readonly API_KEY = 'YOUR_API_KEY';
private readonly BASE_URL = 'https://api.countrydataapi.com/v1/countries';
readonly commonTimezones: TimezoneOption[] = [
{ value: 'UTC-12:00', label: 'UTC-12:00 (Baker Island)' },
{ value: 'UTC-08:00', label: 'UTC-08:00 (Pacific Time)' },
{ value: 'UTC-05:00', label: 'UTC-05:00 (Eastern Time)' },
{ value: 'UTC-03:00', label: 'UTC-03:00 (Brazil)' },
{ value: 'UTC+00:00', label: 'UTC+00:00 (GMT)' },
{ value: 'UTC+01:00', label: 'UTC+01:00 (Central European)' },
{ value: 'UTC+02:00', label: 'UTC+02:00 (Eastern European)' },
{ value: 'UTC+03:00', label: 'UTC+03:00 (Moscow)' },
{ value: 'UTC+05:30', label: 'UTC+05:30 (India)' },
{ value: 'UTC+08:00', label: 'UTC+08:00 (China/Singapore)' },
{ value: 'UTC+09:00', label: 'UTC+09:00 (Japan/Korea)' },
{ value: 'UTC+10:00', label: 'UTC+10:00 (Australia Eastern)' },
{ value: 'UTC+12:00', label: 'UTC+12:00 (New Zealand)' }
];
searchByTimezone(timezone: string): Observable<Country[]> {
const params = new HttpParams()
.set('apikey', this.API_KEY)
.set('timezone', timezone)
.set('fields', 'id,lang,country_name,country_flag_png,country_capital,country_region,country_timezones');
return this.http.get<Country[]>(`${this.BASE_URL}/timezone`, { params }).pipe(
catchError(error => {
console.error('Timezone search error:', error);
return throwError(() => new Error('Failed to search countries by timezone'));
})
);
}
}
// timezone-search.component.ts
import { Component, inject, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TimezoneSearchService, Country } from './timezone-search.service';
@Component({
selector: 'app-timezone-search',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<div class="timezone-search-container">
<h2>Find Countries by Time Zone</h2>
<div class="timezone-selector">
<label for="timezone-select">Select a timezone:</label>
<select
id="timezone-select"
[(ngModel)]="selectedTimezone"
(ngModelChange)="onTimezoneChange($event)"
class="timezone-select"
>
<option value="">-- Select Timezone --</option>
<option *ngFor="let tz of timezoneService.commonTimezones" [value]="tz.value">
{{ tz.label }}
</option>
</select>
</div>
<div *ngIf="loading()" class="loading">Loading countries...</div>
<div *ngIf="error()" class="error-message">{{ error() }}</div>
<div *ngIf="countries().length > 0" class="results">
<h3>{{ countries().length }} countries in {{ selectedTimezone }}</h3>
<div *ngFor="let group of groupedByRegion()" class="region-group">
<h4>{{ group.region }} ({{ group.countries.length }})</h4>
<div class="country-grid">
<div *ngFor="let country of group.countries" class="country-card">
<img
[src]="country.country_flag_png"
[alt]="country.country_name + ' flag'"
class="country-flag"
/>
<div class="country-info">
<strong>{{ country.country_name }}</strong>
<span>{{ formatCapital(country.country_capital) }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
`,
styles: [`
.timezone-search-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.timezone-selector {
margin-bottom: 20px;
}
.timezone-select {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
margin-top: 5px;
}
.region-group {
margin-bottom: 20px;
}
.region-group h4 {
border-bottom: 2px solid #4CAF50;
padding-bottom: 5px;
}
.country-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
}
.country-card {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border: 1px solid #eee;
border-radius: 8px;
}
.country-flag {
width: 40px;
height: auto;
border-radius: 2px;
}
.country-info {
display: flex;
flex-direction: column;
}
.country-info span {
font-size: 0.85em;
color: #666;
}
.loading {
text-align: center;
padding: 20px;
color: #666;
}
.error-message {
color: #dc3545;
padding: 10px;
background-color: #f8d7da;
border-radius: 4px;
}
`]
})
export class TimezoneSearchComponent {
timezoneService = inject(TimezoneSearchService);
selectedTimezone = '';
countries = signal<Country[]>([]);
loading = signal(false);
error = signal<string | null>(null);
groupedByRegion = computed(() => {
const grouped = this.countries().reduce((acc, country) => {
const region = country.country_region || 'Other';
if (!acc[region]) acc[region] = [];
acc[region].push(country);
return acc;
}, {} as Record<string, Country[]>);
return Object.entries(grouped).map(([region, countries]) => ({
region,
countries
}));
});
formatCapital(capital?: string[]): string {
return capital?.join(', ') || 'N/A';
}
onTimezoneChange(timezone: string): void {
if (!timezone) {
this.countries.set([]);
return;
}
this.loading.set(true);
this.error.set(null);
this.timezoneService.searchByTimezone(timezone).subscribe({
next: (data) => {
this.countries.set(data);
this.loading.set(false);
},
error: (err) => {
this.error.set(err.message);
this.countries.set([]);
this.loading.set(false);
}
});
}
}
import requests
from typing import Optional, List, Dict, Any
from dataclasses import dataclass
from collections import defaultdict
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.countrydataapi.com/v1/countries"
# Common timezones
COMMON_TIMEZONES = [
"UTC-12:00", "UTC-11:00", "UTC-10:00", "UTC-09:00", "UTC-08:00",
"UTC-07:00", "UTC-06:00", "UTC-05:00", "UTC-04:00", "UTC-03:00",
"UTC-02:00", "UTC-01:00", "UTC+00:00", "UTC+01:00", "UTC+02:00",
"UTC+03:00", "UTC+04:00", "UTC+05:00", "UTC+05:30", "UTC+06:00",
"UTC+07:00", "UTC+08:00", "UTC+09:00", "UTC+10:00", "UTC+11:00",
"UTC+12:00"
]
@dataclass
class TimezoneCountry:
"""Represents a country in a specific timezone"""
id: str
name: str
flag_url: str
capital: List[str]
region: str
timezones: List[str]
def search_countries_by_timezone(
timezone: str,
fields: Optional[str] = None,
lang: str = "en",
limit_token: int = 1000
) -> List[Dict[str, Any]]:
"""
Search for countries by timezone.
Args:
timezone: The timezone to search for (e.g., "UTC+01:00")
fields: Comma-separated list of fields to return
lang: Language for the response (default: "en")
limit_token: Maximum number of results (default: 1000)
Returns:
List of countries in the specified timezone
"""
params = {
"apikey": API_KEY,
"timezone": timezone,
"lang": lang,
"limitToken": limit_token
}
if fields:
params["fields"] = fields
try:
response = requests.get(f"{BASE_URL}/timezone", params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
raise
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
raise
def get_countries_with_details(timezone: str) -> List[TimezoneCountry]:
"""
Get detailed country information for a timezone.
Args:
timezone: The timezone to search for
Returns:
List of TimezoneCountry objects
"""
fields = "id,lang,country_name,country_flag_png,country_capital,country_region,country_timezones"
countries = search_countries_by_timezone(timezone, fields=fields)
results = []
for country in countries:
results.append(TimezoneCountry(
id=country.get("id", ""),
name=country.get("country_name", ""),
flag_url=country.get("country_flag_png", ""),
capital=country.get("country_capital", []),
region=country.get("country_region", ""),
timezones=country.get("country_timezones", [])
))
return results
def get_countries_grouped_by_region(timezone: str) -> Dict[str, List[TimezoneCountry]]:
"""
Get countries in a timezone grouped by region.
Args:
timezone: The timezone to search for
Returns:
Dictionary with regions as keys and lists of countries as values
"""
countries = get_countries_with_details(timezone)
grouped = defaultdict(list)
for country in countries:
grouped[country.region or "Other"].append(country)
return dict(grouped)
def analyze_timezone_coverage():
"""Analyze which timezones have the most countries."""
results = {}
for tz in COMMON_TIMEZONES:
try:
countries = search_countries_by_timezone(tz)
results[tz] = len(countries)
print(f"{tz}: {len(countries)} countries")
except Exception as e:
results[tz] = 0
print(f"{tz}: Error - {e}")
return results
# Example usage
if __name__ == "__main__":
# Basic search
print("Countries in UTC+01:00 (Central European Time):")
countries = search_countries_by_timezone("UTC+01:00")
for country in countries[:5]:
print(f" - {country.get('country_name')}")
print(f" ... and {len(countries) - 5} more\n")
# Get detailed information
print("Countries in UTC+05:30 (India Standard Time):")
detailed = get_countries_with_details("UTC+05:30")
for country in detailed:
print(f" - {country.name} (Capital: {', '.join(country.capital)})")
# Group by region
print("\nCountries in UTC+00:00 grouped by region:")
grouped = get_countries_grouped_by_region("UTC+00:00")
for region, region_countries in grouped.items():
print(f" {region}: {len(region_countries)} countries")
<?php
class CountryTimezoneSearch
{
private string $apiKey;
private string $baseUrl = 'https://api.countrydataapi.com/v1/countries';
// Common timezones for reference
public const COMMON_TIMEZONES = [
'UTC-12:00' => 'Baker Island',
'UTC-08:00' => 'Pacific Time (US)',
'UTC-05:00' => 'Eastern Time (US)',
'UTC-03:00' => 'Brazil',
'UTC+00:00' => 'GMT/UTC',
'UTC+01:00' => 'Central European',
'UTC+02:00' => 'Eastern European',
'UTC+03:00' => 'Moscow',
'UTC+05:30' => 'India',
'UTC+08:00' => 'China/Singapore',
'UTC+09:00' => 'Japan/Korea',
'UTC+10:00' => 'Australia Eastern',
'UTC+12:00' => 'New Zealand'
];
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
/**
* Search for countries by timezone
*
* @param string $timezone The timezone (e.g., "UTC+01:00")
* @param array $options Additional options
* @return array List of countries
* @throws Exception
*/
public function searchByTimezone(string $timezone, array $options = []): array
{
$params = array_merge([
'apikey' => $this->apiKey,
'timezone' => $timezone
], $options);
$url = $this->baseUrl . '/timezone?' . http_build_query($params);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER => [
'Accept: application/json'
]
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new Exception("cURL Error: $error");
}
if ($httpCode !== 200) {
throw new Exception("HTTP Error: $httpCode");
}
return json_decode($response, true) ?? [];
}
/**
* Get countries with detailed information
*
* @param string $timezone The timezone to search
* @return array Countries with full details
*/
public function getCountriesWithDetails(string $timezone): array
{
return $this->searchByTimezone($timezone, [
'fields' => 'id,lang,country_name,country_flag_png,country_capital,country_region,country_timezones'
]);
}
/**
* Get countries grouped by region
*
* @param string $timezone The timezone to search
* @return array Countries grouped by region
*/
public function getCountriesGroupedByRegion(string $timezone): array
{
$countries = $this->getCountriesWithDetails($timezone);
$grouped = [];
foreach ($countries as $country) {
$region = $country['country_region'] ?? 'Other';
if (!isset($grouped[$region])) {
$grouped[$region] = [];
}
$grouped[$region][] = $country;
}
return $grouped;
}
/**
* Count countries per timezone
*
* @param array $timezones List of timezones to check
* @return array Timezone => country count mapping
*/
public function countCountriesPerTimezone(array $timezones = null): array
{
$timezones = $timezones ?? array_keys(self::COMMON_TIMEZONES);
$results = [];
foreach ($timezones as $tz) {
try {
$countries = $this->searchByTimezone($tz);
$results[$tz] = count($countries);
} catch (Exception $e) {
$results[$tz] = 0;
}
}
return $results;
}
}
// Example usage
$apiKey = 'YOUR_API_KEY';
$timezoneSearch = new CountryTimezoneSearch($apiKey);
try {
// Search by timezone
echo "Countries in UTC+01:00 (Central European Time):\n";
$countries = $timezoneSearch->searchByTimezone('UTC+01:00');
foreach (array_slice($countries, 0, 5) as $country) {
echo " - " . $country['country_name'] . "\n";
}
echo " ... and " . (count($countries) - 5) . " more\n\n";
// Get detailed information
echo "Countries in UTC+05:30 (India Standard Time):\n";
$detailed = $timezoneSearch->getCountriesWithDetails('UTC+05:30');
foreach ($detailed as $country) {
$capital = implode(', ', $country['country_capital'] ?? []);
echo " - " . $country['country_name'] . " (Capital: $capital)\n";
}
// Group by region
echo "\nCountries in UTC+00:00 grouped by region:\n";
$grouped = $timezoneSearch->getCountriesGroupedByRegion('UTC+00:00');
foreach ($grouped as $region => $regionCountries) {
echo " $region: " . count($regionCountries) . " countries\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
| Status Code | Description |
|---|---|
| 200 | Success - Returns array of countries |
| 400 | Bad Request - Invalid or missing timezone parameter |
| 401 | Unauthorized - Invalid or missing API key |
| 404 | Not Found - No countries found with the given timezone |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server-side error |