How to Display Local Time with Daylight Saving Using IP2Location.io

Display Local Time with Daylight Saving Using IP2Location.io

Displaying local time correctly is crucial for both website owners and visitors. By showing the local time, including daylight saving adjustments on a website, visitors can understand date and time information accurately. This improves clarity for time-sensitive content and helps minimize potential confusion or misunderstandings.

Incorrect timezone usage can lead to various issues and inconveniences. For example, users might misinterpret important information such as delivery dates or the start and end times of a promotional event. Inaccurate timezone handling can also cause miscommunication. Imagine a scenario where one person is in the United States and another is in Japan, with an online meeting scheduled at 2:00 PM UTC+0. If either side misreads the time, they could end up missing the meeting entirely.

To help users identify the correct timezone and handle Daylight Saving Time (DST) effectively, IP2Location.io had recently introduced new fields in the API response, namely abbreviation, dst_start_date, and dst_end_date. These, combined with the existing timezone information, enable developers to manage datetime data across multiple regions effectively and effortlessly. 

Using IP2Location.io to Get Timezone Info

To get the result that contains the new fields, you just need to call the API again, for example https://api.ip2location.io/?key={YOUR_API_KEY}&ip=8.8.8.8&format=json for the IP 8.8.8.8. You will see the output as below:

{
  "ip": "8.8.8.8",
  "country_code": "US",
  "country_name": "United States of America",
  "region_name": "California",
  "district": "Santa Clara County",
  "city_name": "Mountain View",
  "latitude": 37.38605,
  "longitude": -122.08385,
  "zip_code": "94035",
  "time_zone": "-07:00",
  "asn": "15169",
  "as": "Google LLC",
  "isp": "Google LLC",
  "domain": "google.com",
  "net_speed": "T1",
  "idd_code": "1",
  "area_code": "650",
  "weather_station_code": "USCA0746",
  "weather_station_name": "Mountain View",
  "mcc": "-",
  "mnc": "-",
  "mobile_brand": "-",
  "elevation": 32,
  "usage_type": "DCH",
  "address_type": "Anycast",
  "ads_category": "IAB19-11",
  "ads_category_name": "Data Centers",
  "continent": {
    "name": "North America",
    "code": "NA",
    "hemisphere": [
      "north",
      "west"
    ],
    "translation": {
      "lang": null,
      "value": null
    }
  },
  "country": {
    "name": "United States of America",
    "alpha3_code": "USA",
    "numeric_code": 840,
    "demonym": "Americans",
    "flag": "https://cdn.ip2location.io/assets/img/flags/us.png",
    "capital": "Washington, D.C.",
    "total_area": 9826675,
    "population": 339665118,
    "currency": {
      "code": "USD",
      "name": "United States Dollar",
      "symbol": "$"
    },
    "language": {
      "code": "EN",
      "name": "English"
    },
    "tld": "us",
    "translation": {
      "lang": null,
      "value": null
    }
  },
  "region": {
    "name": "California",
    "code": "US-CA",
    "translation": {
      "lang": null,
      "value": null
    }
  },
  "city": {
    "name": "Mountain View",
    "translation": {
      "lang": null,
      "value": null
    }
  },
  "time_zone_info": {
    "olson": "America/Los_Angeles",
    "current_time": "2025-07-30T21:08:34-07:00",
    "gmt_offset": -25200,
    "is_dst": true,
    "abbreviation": "PDT",
    "dst_start_date": "2025-03-09",
    "dst_end_date": "2025-11-02",
    "sunrise": "06:11",
    "sunset": "20:18"
  },
  "geotargeting": {
    "metro": "807"
  },
  "is_proxy": false,
  "fraud_score": 0,
  "proxy": {
    "last_seen": 1,
    "proxy_type": "DCH",
    "threat": "-",
    "provider": "-",
    "is_vpn": false,
    "is_tor": false,
    "is_data_center": true,
    "is_public_proxy": false,
    "is_web_proxy": false,
    "is_web_crawler": false,
    "is_residential_proxy": false,
    "is_consumer_privacy_network": false,
    "is_enterprise_private_network": false,
    "is_spammer": false,
    "is_scanner": false,
    "is_botnet": false,
    "is_bogon": false
  }
}

Note: The abbreviation, dst_start, and dst_end fields are only available for the Plus and Security plan user. Please purchase the plan before proceeding.

Convert UTC to Local Time

To convert a UTC timestamp to the user’s local time, you can use the time_zone_info >> olson

value (e.g., America/New_York) returned from the IP2Location.io API. Most modern programming languages have built-in libraries that allow you to apply this timezone directly to a UTC datetime, automatically adjusting for daylight saving time if applicable.

Below are the example code snippet that can be used to convert a UTC time to local time:

<?php
$apiKey = 'YOUR_API_KEY';
$ip = $_SERVER['REMOTE_ADDR'];

// Call the IP2Location.io API
$apiUrl = "https://api.ip2location.io/?key=$apiKey&ip=$ip";
$response = file_get_contents($apiUrl);
$data = json_decode($response, true);

// Get the Olson timezone from time_zone_info
$olson = $data['time_zone_info']['olson'] ?? 'UTC';

// Create and format local time
$utcTime = new DateTime('now', new DateTimeZone('UTC'));
$localTime = $utcTime->setTimezone(new DateTimeZone($olson));

echo "Local time in $olson: " . $localTime->format('Y-m-d H:i:s T');
?>
import requests
from datetime import datetime
from zoneinfo import ZoneInfo  # Python 3.9+

api_key = "YOUR_API_KEY"
ip = "8.8.8.8"  # Example, can change accordingly

# Fetch data from IP2Location.io
response = requests.get(f"https://api.ip2location.io/?key={api_key}&ip={ip}")
data = response.json()

# Extract Olson timezone
olson = data.get("time_zone_info", {}).get("olson", "UTC")

# Convert and format local time
utc_now = datetime.now().replace(tzinfo=ZoneInfo("UTC"))
local_time = utc_now.astimezone(ZoneInfo(olson))

print(f"Local time in {olson}: {local_time.strftime('%Y-%m-%d %H:%M:%S %Z')}")
const fetch = require('node-fetch');
const { DateTime } = require('luxon'); // Both are installable using npm install node-fetch@2 luxon

const apiKey = 'YOUR_API_KEY';
const ip = '8.8.8.8'; // Replace with actual IP

(async () => {
  const response = await fetch(`https://api.ip2location.io/?key=${apiKey}&ip=${ip}`);
  const data = await response.json();

  const olson = data.time_zone_info?.olson || 'UTC';

  const localTime = DateTime.utc().setZone(olson);
  console.log(`Local time in ${olson}: ${localTime.toFormat('yyyy-MM-dd HH:mm:ss ZZZZ')}`);
})();

Handling DST & Display Time on Website

The dst_start and dst_end fields definitely come in handy especially if you need to solve the time issue in the countries that are observing DST. By utilizing both fields, you can easily determine whether the country is currently observing DST.

Nowadays, most timezone libraries automatically take into account when calculating the local time for those countries that are observing DST. Most of the time, by using the library, you will not have a problem getting the accurate local time calculated with the DST factored in. However, sometimes the government may choose to continue observing the DST in the upcoming year or not. If the libraries haven’t been updated to handle the changes, you still can use IP2Location.io API result to make a quick check on whether the DST is in effect or not.

Below is a simple example of how to show the formatted local time in a website:

<?php
// Replace with your actual API key
$apiKey = 'YOUR_API_KEY';
// Get the user's IP address (fallbacks to REMOTE_ADDR if not behind proxy)
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];

// Call IP2Location.io API
$apiUrl = "https://api.ip2location.io/?key=$apiKey&ip=$ip";
$response = file_get_contents($apiUrl);
$data = json_decode($response, true);

// Fallback timezone
$timezone = $data['timezone'] ?? 'UTC';

// Create datetime in user's local timezone
$utc = new DateTime('now', new DateTimeZone('UTC'));
$local = $utc->setTimezone(new DateTimeZone($timezone));
$formattedTime = $local->format('Y-m-d H:i:s T');
?>
<!DOCTYPE html>
<html>
<head>
  <title>Local Time Display</title>
</head>
<body>
  <p>Your local time is: <strong><?php echo $formattedTime; ?></strong></p>
</body>
</html>

Conclusion

Displaying accurate local time for your user isn’t a difficult task. With IP2Location.io IP Geolocation API, you can easily achieve the mission in a few steps, starting with detecting the user’s IP address, fetching the timezone information, and converting and displaying the local time. The IP2Location.io API will benefit you in many ways, such as improving user experience, ensuring effective communication, and delivering accurate datetime information — including adjustments for daylight saving time where applicable.

Was this article helpful?

Related Articles