Apart from using an API to get a user's TimeZone, is there any other way to get user's TimeZone, maybe like using JavaScript to get a user's TimeZone?
Apart from the below code, can any other means that can be used to get a user's TimeZone?
Namespaces
using System.Linq;
using System.Net;
using System.Web.Script.Serialization;
C#
protected void Page_Load(object sender, EventArgs e)
{
LoginDateTime();
}
private Location GetLocation()
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
string APIKey = "API_Key";
string url = string.Format("https://api.ip2location.io/?key={0}&ip={1}&format=json", APIKey, ipAddress);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
using (WebClient client = new WebClient())
{
string json = client.DownloadString(url);
Location location = new JavaScriptSerializer().Deserialize<Location>(json);
return location;
}
}
private void LoginDateTime()
{
DateTime time1 = Convert.ToDateTime("2023/06/19 22:25");
TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(GetTimeZoneNameByOffsetTime(this.GetLocation().time_zone.Replace("+", "")));
DateTime userLocalTime = TimeZoneInfo.ConvertTime(time1, serverTimeZone, userTimeZone);
Timelbl.Text = userLocalTime.ToString("dddd, MMMM d, yyyy h:mm tt");
}
public string GetTimeZoneNameByOffsetTime(string offset)
{
return TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.BaseUtcOffset == TimeSpan.Parse(offset)).StandardName;
}
public class Location
{
public string ip { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public string region_name { get; set; }
public string city_name { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string zip_code { get; set; }
public string time_zone { get; set; }
public string asn { get; set; }
public string @as { get; set; }
public bool is_proxy { get; set; }
}