Send Javascript UTC from client to Classic ASP application with Query String - javascript

I'm trying to convert a local time event - 8AM - stored on db - to the client's local time in another country.
Event in Mexico City 8AM to Paris, for example.
I don't know JS but I can identify the local time in the client machine with this:
<script>
function myFunction() {
var d = new Date();
var n = d.getTimezoneOffset();
}
</script>
Now I trying to send this value to CLASSIC ASP - back to server.
To do this I trying to create a link to send the information in a query string.
www.domain.com/login.asp?utc=XXXX
THen I can get the UTC time from client and convert with Classic ASP (I have better knowledge of Classic ASP)
Another easy way is to create a SESSION in JS - but I don't know how and I it's works with CLassic ASP sessions too.
Any idea?
tks!
Daniel

I would recommend using browser cookies and Classic ASP's Response.Cookies collection to do this. The Javascript to do this is pretty simple:
// get the current date from the user's local machine
var now = new Date();
/*
The getTimezoneOffset() function returns the timezone offset in minutes.
If you want to convert dates from UTC to the user's local time
based on the timezone the user has set on their machine you need to
multiple the result by -1.
This method does have the caveat that it assumes the user has set
their local machine's timezone information correctly.
*/
var offset = -now.getTimezoneOffset();
// write a cookie to the user's browser with the offset
document.cookie = "offset_to_utc="+offset
You could check to see if the cookie already exists rather than checking the user's timezone each time; however, if the user changes their timezone information during the same session, the change would not be reflected.
On the next page load and any page loads in the same browser session, you can retrieve the cookie you just set on the server side using Response.Cookies:
Dim OffsetToUTC
OffsetToUTC = Response.Cookies("offset_to_utc").Value
'Since cookies can be modified by users, it is a good idea to check the type
'of the data retrieved and convert it to an integer only if it is numeric.
If IsNumeric(OffsetToUTC) Then
OffsetToUTC = CInt(OffsetToUTC)
Else
OffsetToUTC = 0
End If
To convert a date in the database stored in UTC to the user's local time would look something like this:
Dim DBDate
DBDate = '<Replace with your code to get the date from the database>'
Response.Write(DateAdd("n", OffsetToUTC, DBDate))

Related

Issue converting Luxon date to a selected Time Zone from user cookie

I am working on a web application that needs stores a start and finish value for a work shift. The application has a timezone selection component which updates any date/time values in UI to match the time in a given timezone/location by changing a timezone cookie. Values are stored in a database as UTC values and they are passed through a controller to convert them between the DB and UI.
I am working on a page that has an exception where the start and finish times are changeable/editable by the user after saving. The page will get these values from UI Date Boxes. The values can convert to UTC on saving values with no issue with use of Luxon, however, a user can navigate back to the given page to edit saved values if changes are needed. When this happens, the saved values are loaded into these DevExpress/DevExtreme date boxes but they are not displayed as expected.
The values come from an odata response and is read as response.value[0].Start. When getting the value, an offset is applied based on the users cookie location, so in my case (Europe/London timezone) the response would be 2022-05-24T01:00:00+01:00.
I can convert this to UTC using DateTime.fromISO(response.value[0].Start).toUTC() to give me a value of 2022-05-24T00:00:00.000Z which is expected.
However I am running into converting this value to the desired value for a selected timezone. I try to do so with the following:
var DateTime = luxon.DateTime;
//selectedTimeZone found from cookie.
// -- logic --
if (response.value[0].Start != null) {
var dateBox = $("#ShiftBeginning").dxDateBox('instance');
var converted = DateTime.fromISO(response.value[0].Start).toUTC().setZone(selectedTimeZone, {keepLocalTime: true});
dateBox.option({ value: converted});
}
//Example selectedTimeZone: Asia/Tokyo
//converted.toString() value: 2022-05-24T00:00:00.000+09:00 (Tokyo time zone)
//Displayed UI Time value: 16:00
//Displayed UI Time value with {keepLocalTime: false}: 01:00
It appears as if the value of converted is having the offset applied twice, with an hour then taken off of the time to represent UTC.
I have tried changing parsing this value to different formats, tested different timezones, using standard JavaScript Date object etc. and I am beginning to run out of ideas.
Any help is appreciated to help solve this.
It's being "converted" twice because the time picker doesn't respect the zone in your cookie, because it doesn't know about it. Remember that the time is the time; the zone and how the time is represented in that zone are more like metadata. So it's expressing the time in user's system zone, and the local time it displays is off from what you expect by the difference between where they are and Tokyo's local time.
What you want to do is:
find the local time in Tokyo for your time. This is probably just DateTime.fromISO(s).setZone(selectedZone). You don't want keepLocalTime because your time is correct
change to the user's system zone, but keeping the time constant, which is just converted.setZone("system", { keepLocalTime: true }). We do this because we want a local time that is, technically, wrong; it's what local time matches the right Tokyo time. This is more-or-less the purpose of keepLocalTime: to trick zone-unaware components into showing a local time in another zone.
It's a little odd that you're passing the Luxon DateTime directly to the time picker. I guess it's calling valueOf() on the value you pass in. But you'd probably want to do that yourself to be confident you're telling it the right thing.
So all together:
var converted = DateTime
.fromISO(response.value[0].Start)
.setZone(selectedTimeZone);
.setZone("system", { keepLocalTime: true });
dateBox.option({ value: converted.valueOf() });

(Sanity Check) Do I need a timezone library for this simple use case?

This will be my first time working with time zones, I hear this is a major pain point for a lot of developers so I'm asking this question as a sanity check to make sure I'm not missing anything.
My use case is rather "simple", I want to have a date time picker where the user can choose their date and time in their local timezone (in other words what they see in the picker matches what their computer's date and time is set to).
Then I want to take this chosen date and time, convert it to UTC and send it to the server to be saved.
When the user goes to certain pages I take the UTC date/time coming back from the server and convert it to the user's local date/time and display it to them in a user friendly way.
Do I need a library like moment timezone for this or will the browser's native date methods like Intl.DateTimeFormat, new Date().getTimezoneOffset(), etc be enough? (I only need to support the latest modern browsers so I'm asking this from a "does it do what I need" ​point of view not a browser support POV).
It seems all I need are 2 things:
A way to get the user's timezone offset from UTC (so I can convert their local time to UTC to send to the server and also to convert UTC back to their local time to display it to them on certain pages)
A way get their timezone abbreviation (EST, PDT, CDT, etc) to show in the UI
Do I need a library for these? And if not why do people use such large libraries for working with timezones anyway?
You don't need a time zone library for the functionality you mentioned.
// Get a Date object from your date picker, or construct one
const d1 = new Date("2020-08-02T10:00");
// Convert it to a UTC-based ISO 8601 string for your back-end
const utcString = d1.toISOString();
// Later, you can create a new Date object from the UTC string
const d2 = new Date(utcString);
// And you can display it in local time
const s1 = d2.toString();
// Or you can be a bit more precise with output formatting if you like
const s2 = d2.toLocaleString(undefined, {timeZoneName: 'short'});
console.log("UTC: ", utcString);
console.log("Local Time (default string): ", s1);
console.log("Local Time (intl-based string): ", s2);
Keep in mind that not all time zones will have an abbreviation, so those ones will give output like "GMT+3".

Javascript - displaying locale time from mySQL TimeDate

I am having an issue with displaying the correct time. I have a php script that when a button is clicked it inserts the CURRENT_TIMESTAMP into the database. The server is located in Arizona, I am in PST. When I call the time in my script it shows Arizona time, but I need it to show the users time. So 2015-02-18 16:06:28 Arizona time, MY time is 2015-02-18 15:06:28.
How do i get the correct time. I am using moment.js, but no matter how i format it it shows the incorrect time. I am not sure but is DST, not being considered?
var time_in = time_in;//format 2015-02-18 16:17:33
var timeIn = moment.utc(time_in, "HH:mm a").format("HH:mm a");
Moment.js parses the date as a locale date-time. So when you do moment.utc(time_in), you're converting it to UTC according to your local time (PST), shifted forward or backwards.
So what you need to do is do a moment.fn.utcOffset. Arizona is UTC-07:00, so we would want to add +7 to the offset. You can do the same using moment.fn.zone but that's getting deprecated.
var utcTime = moment.utc('2015-02-18 16:06:28').utcOffset(+7).format('YYYY-MM-DD HH:mm:ss')
// returns "2015-02-18 23:06:28" which is the UTC time
Now you have the moment in UTC, you can convert it to the client localtime:
moment(moment.utc(utcTime).toDate()).format('YYYY-MM-DD HH:mm:ss')
// returns '2015-02-18 15:06:28' (which is PST)
moment.utc(utcTime).toDate() above just converts the utc time to your local time, then formatting it with momentjs
EDIT: If possible, you should use unix timestamp when sending to server, then you don't have to deal with UTC or timezones. You can convert to local time with moment.unix(unixTimestamp).format('YYYY-MM-DD HH:mm:ss')
It looks like you are using Javascript to get the time of the client, but then not passing that to the PHP. I'm not sure how your app is structured, but you could create an input tag with the type="hidden". Then using Javascript, find the element and set it's value to Date().
Here is an example: http://jsfiddle.net/43jfefuq/
Now when you submit this form with PHP, the value in the field will be the client's local time.

Why is the client time zone (not offset) not available in the browser? [duplicate]

Is there a standard way for a web server to be able to determine a user's timezone within a web page?
Perhaps from an HTTP header or part of the user-agent string?
-new Date().getTimezoneOffset()/60;
The method getTimezoneOffset() will subtract your time from GMT and return the number of minutes. So if you live in GMT-8, it will return 480.
To put this into hours, divide by 60. Also, notice that the sign is the opposite of what you need - it's calculating GMT's offset from your time zone, not your time zone's offset from GMT. To fix this, simply multiply by -1.
Also note that w3school says:
The returned value is not a constant, because of the practice of using
Daylight Saving Time.
The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such.
I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context.
There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification.
If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something.
First, understand that time zone detection in JavaScript is imperfect. You can get the local time zone offset for a particular date and time using getTimezoneOffset on an instance of the Date object, but that's not quite the same as a full IANA time zone like America/Los_Angeles.
There are some options that can work though:
Most modern browsers support IANA time zones in their implementation of the ECMAScript Internationalization API, so you can do this:
const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(tzid);
The result is a string containing the IANA time zone setting of the computer where the code is running.
Supported environments are listed in the Intl compatibility table. Expand the DateTimeFormat section, and look at the feature named resolvedOptions().timeZone defaults to the host environment.
Some libraries, such as Luxon use this API to determine the time zone through functions like luxon.Settings.defaultZoneName.
If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the Intl API if it's available, and when it's not available, they interrogate the getTimezoneOffset function of the Date object, for several different points in time, using the results to choose an appropriate time zone from an internal data set.
Both jsTimezoneDetect and moment-timezone have this functionality.
// using jsTimeZoneDetect
var tzid = jstz.determine().name();
// using moment-timezone
var tzid = moment.tz.guess();
In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them.
Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here.
Ultimately, a better approach is to actually ask your user for their time zone. Provide a setting that they can change. You can use one of the above options to choose a default setting, but don't make it impossible to deviate from that in your app.
There's also the entirely different approach of not relying on the time zone setting of the user's computer at all. Instead, if you can gather latitude and longitude coordinates, you can resolve those to a time zone using one of these methods. This works well on mobile devices.
JavaScript is the easiest way to get the client's local time. I would suggest using an XMLHttpRequest to send back the local time, and if that fails, fall back to the timezone detected based on their IP address.
As far as geolocation, I've used MaxMind GeoIP on several projects and it works well, though I'm not sure if they provide timezone data. It's a service you pay for and they provide monthly updates to your database. They provide wrappers in several web languages.
Here is a robust JavaScript solution to determine the time zone the browser is in.
>>> var timezone = jstz.determine();
>>> timezone.name();
"Europe/London"
https://github.com/pellepim/jstimezonedetect
Here is a more complete way.
Get the timezone offset for the user
Test some days on daylight saving boundaries to determine if they are in a zone that uses daylight saving.
An excerpt is below:
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
// Go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
// To ignore daylight saving time look for the lowest offset.
// Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
Getting TZ and DST from JS (via Way Back Machine)
Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work!
On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>, you need to first of all include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>, below the jQuery, paste this:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.org/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the URL to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this:
(create a new file called timezone.php and point to it with the above URL)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
To submit the timezone offset as an HTTP header on AJAX requests with jQuery
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60);
}
});
You can also do something similar to get the actual time zone name by using moment.tz.guess(); from http://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/
I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset.
Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset.
If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much.
Now, to get the time zone with javascript you can use this:
>> new Date().toTimeString();
"15:46:04 GMT+1200 (New Zealand Standard Time)"
//Use some regular expression to extract the time.
However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone:
https://github.com/scottwater/jquery.detect_timezone
With the PHP date function you will get the date time of server on which the site is located. The only way to get the user time is to use JavaScript.
But I suggest you to, if your site has registration required then the best way is to ask the user while to have registration as a compulsory field. You can list various time zones in the register page and save that in the database. After this, if the user logs in to the site then you can set the default time zone for that session as per the users’ selected time zone.
You can set any specific time zone using the PHP function date_default_timezone_set. This sets the specified time zone for users.
Basically the users’ time zone is goes to the client side, so we must use JavaScript for this.
Below is the script to get users’ time zone using PHP and JavaScript.
<?php
#http://www.php.net/manual/en/timezones.php List of Time Zones
function showclienttime()
{
if(!isset($_COOKIE['GMT_bias']))
{
?>
<script type="text/javascript">
var Cookies = {};
Cookies.create = function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else {
var expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
this[name] = value;
}
var now = new Date();
Cookies.create("GMT_bias",now.getTimezoneOffset(),1);
window.location = "<?php echo $_SERVER['PHP_SELF'];?>";
</script>
<?php
}
else {
$fct_clientbias = $_COOKIE['GMT_bias'];
}
$fct_servertimedata = gettimeofday();
$fct_servertime = $fct_servertimedata['sec'];
$fct_serverbias = $fct_servertimedata['minuteswest'];
$fct_totalbias = $fct_serverbias – $fct_clientbias;
$fct_totalbias = $fct_totalbias * 60;
$fct_clienttimestamp = $fct_servertime + $fct_totalbias;
$fct_time = time();
$fct_year = strftime("%Y", $fct_clienttimestamp);
$fct_month = strftime("%B", $fct_clienttimestamp);
$fct_day = strftime("%d", $fct_clienttimestamp);
$fct_hour = strftime("%I", $fct_clienttimestamp);
$fct_minute = strftime("%M", $fct_clienttimestamp);
$fct_second = strftime("%S", $fct_clienttimestamp);
$fct_am_pm = strftime("%p", $fct_clienttimestamp);
echo $fct_day.", ".$fct_month." ".$fct_year." ( ".$fct_hour.":".$fct_minute.":".$fct_second." ".$fct_am_pm." )";
}
showclienttime();
?>
But as per my point of view, it’s better to ask to the users if registration is mandatory in your project.
Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside.
Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability.
IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct.
JavaScript:
function maketimus(timestampz)
{
var linktime = new Date(timestampz * 1000);
var linkday = linktime.getDate();
var freakingmonths = new Array();
freakingmonths[0] = "jan";
freakingmonths[1] = "feb";
freakingmonths[2] = "mar";
freakingmonths[3] = "apr";
freakingmonths[4] = "may";
freakingmonths[5] = "jun";
freakingmonths[6] = "jul";
freakingmonths[7] = "aug";
freakingmonths[8] = "sep";
freakingmonths[9] = "oct";
freakingmonths[10] = "nov";
freakingmonths[11] = "dec";
var linkmonthnum = linktime.getMonth();
var linkmonth = freakingmonths[linkmonthnum];
var linkyear = linktime.getFullYear();
var linkhour = linktime.getHours();
var linkminute = linktime.getMinutes();
if (linkminute < 10)
{
linkminute = "0" + linkminute;
}
var fomratedtime = linkday + linkmonth + linkyear + " " +
linkhour + ":" + linkminute + "h";
return fomratedtime;
}
Simply provide your times in Unix timestamp format to this function; JavaScript already knows the timezone of the user.
Like this:
PHP:
echo '<script type="text/javascript">
var eltimio = maketimus('.$unix_timestamp_ofshiz.');
document.write(eltimio);
</script><noscript>pls enable javascript</noscript>';
This will always show the times correctly based on the timezone the person has set on his/her computer clock. There is no need to ask anything to anyone and save it into places, thank god!
Easy, just use the JavaScript getTimezoneOffset function like so:
-new Date().getTimezoneOffset()/60;
All the magic seems to be in
visitortime.getTimezoneOffset()
That's cool, I didn't know about that. Does it work in Internet Explorer etc? From there you should be able to use JavaScript to Ajax, set cookies whatever. I'd probably go the cookie route myself.
You'll need to allow the user to change it though. We tried to use geo-location (via maxmind) to do this a while ago, and it was wrong enough to make it not worth doing. So we just let the user set it in their profile, and show a notice to users who haven't set theirs yet.
If you happen to be using OpenID for authentication, Simple Registration Extension would solve the problem for authenticated users (You'll need to convert from tz to numeric).
Another option would be to infer the time zone from the user agent's country preference. This is a somewhat crude method (won't work for en-US), but makes a good approximation.
Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application:
It's About Time
In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET).
It is simple with JavaScript and PHP:
Even though the user can mess with his/her internal clock and/or timezone, the best way I found so far, to get the offset, remains new Date().getTimezoneOffset();. It's non-invasive, doesn't give head-aches and eliminates the need to rely on third parties.
Say I have a table, users, that contains a field date_created int(13), for storing Unix timestamps;
Assuming a client creates a new account, data is received by post, and I need to insert/update the date_created column with the client's Unix timestamp, not the server's.
Since the timezoneOffset is needed at the time of insert/update, it is passed as an extra $_POST element when the client submits the form, thus eliminating the need to store it in sessions and/or cookies, and no additional server hits either.
var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets
var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;
Say the server receives tzo as $_POST['tzo'];
$ts = new DateTime('now', new DateTimeZone($_POST['tzo']);
$user_time = $ts->format("F j, Y, g:i a");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.
$user_timestamp = strtotime($user_time);
Insert/update date_created=$user_timestamp.
When retrieving the date_created, you can convert the timestamp like so:
$date_created = // Get from the database
$created = date("F j, Y, g:i a",$date_created); // Return it to the user or whatever
Now, this example may fit one's needs, when it comes to inserting a first timestamp... When it comes to an additional timestamp, or table, you may want to consider inserting the tzo value into the users table for future reference, or setting it as session or as a cookie.
P.S. BUT what if the user travels and switches timezones. Logs in at GMT+4, travels fast to GMT-1 and logs in again. Last login would be in the future.
I think... we think too much.
You could do it on the client with moment-timezone and send the value to server; sample usage:
> moment.tz.guess()
"America/Asuncion"
Getting a valid TZ Database timezone name in PHP is a two-step process:
With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
Pass this offset to PHP.
In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.
// Just an example.
$timezone_offset_minutes = -360; // $_GET['timezone_offset_minutes']
// Convert minutes to seconds
$timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
// America/Chicago
echo $timezone_name;</code></pre>
I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.
Try this PHP code:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.easyjquery.com/ips/?ip=" . $ip . "&full=true");
$json = json_decode($json,true);
$timezone = $json['LocalTimeZone'];
?>
A simple way to do it is by using:
new Date().getTimezoneOffset();
Here's how I do it. This will set the PHP default timezone to the user's local timezone. Just paste the following on the top of all your pages:
<?php
session_start();
if(!isset($_SESSION['timezone']))
{
if(!isset($_REQUEST['offset']))
{
?>
<script>
var d = new Date()
var offset= -d.getTimezoneOffset()/60;
location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset;
</script>
<?php
}
else
{
$zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);
$index = array_keys($zonelist, $_REQUEST['offset']);
$_SESSION['timezone'] = $index[0];
}
}
date_default_timezone_set($_SESSION['timezone']);
//rest of your code goes here
?>
One possible option is to use the Date header field, which is defined in RFC 7231 and is supposed to include the timezone. Of course, it is not guaranteed that the value is really the client's timezone, but it can be a convenient starting point.
There can be a few ways to determine the timezone in the browser. If there is a standard function that is available and supported by your browser, that is what you should use. Below are three ways to get the same information in different formats. Avoid using non-standard solutions that make any guesses based on certain assumptions or hard coded lists of zones though they may be helpful if nothing else can be done.
Once you have this info, you can pass this as a non-standard request header to server and use it there. If you also need the timezone offset, you can also pass it to server in headers or in request payload which can be retrieved with dateObj.getTimezoneOffset().
Use Intl API to get the Olson format (Standard and recommended way): Note that this is not supported by all browsers. Refer this link for details on browser support for this.
This API let's you get the timezone in Olson format i.e., something like Asia/Kolkata, America/New_York etc.
Intl.DateTimeFormat().resolvedOptions().timeZone
Use Date object to get the long format such as India Standard Time, Eastern Standard Time etc: This is supported by all browsers.
let dateObj = new Date(2021, 11, 25, 09, 30, 00);
//then
dateObj.toString()
//yields
Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time) //I am located in India (IST)
Notice the string contains timezone info in long and short formats. You can now use regex to get this info out:
let longZoneRegex = /\((.+)\)/;
dateObj.toString().match(longZoneRegex);
//yields
['(India Standard Time)', 'India Standard Time', index: 34, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]
//Note that output is an array so use output[1] to get the timezone name.
Use Date object to get the short format such as GMT+0530, GMT-0500 etc: This is supported by all browsers.
Similarly, you can get the short format out too:
let shortZoneRegex = /GMT[+-]\d{1,4}/;
dateObj.toString().match(shortZoneRegex);
//yields
['GMT+0530', index: 25, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]
//Note that output is an array so use output[0] to get the timezone name.
There's no such way to figure the timezone in the actual HTML code or any user-agent string, but what you can do is make a basic function getting it using JavaScript.
I don't know how to code with JavaScript yet so my function might take time to make.
However, you can try to get the actual timezone also using JavaScript with the getTzimezoneOffset() function in the Date section or simply new Date().getTimezoneOffset();.
I think that #Matt Johnson-Pints is by far the best and a CanIuse search reveals that now it is widely adopted:
https://caniuse.com/?search=Intl.DateTimeFormat().resolvedOptions().timeZone
One of the challenges though is to consider why you want to know the Timezone. Because I think one of the things most people have missed is that they can change! If a user travels with his laptop from Europe to America if you had previously stored it in a database their timezone is now incorrect (even if the user never actually updates their devices timezone). This is also the problem with #Mads Kristiansen answer as well because users travel - you cannot rely on it as a given.
For example, my Linux laptop has "automatic timezone" turned off. Whilst the time might update my timezone doesn't.
So I believe the answer is - what do you need it for? Client side certainly seems to give an easier way to ascertain it, but both client and server side code will depend on either the user updating their timezone or it updating automatically. I might of course be wrong.

Display Browser specific date/time using extjs

I have a database field called CreatedDate which is a timestamp field and holds the date and time. It currently holds the GMT time.
At the moment this field is displayed as it is on the web pages.
We want to amend this to show date/time as per browser local time zone
Can you please let us know how we can do this.
Thanks in advance
If you can represent the universal time as a count of milliseconds since the 1 Jan 1970 epoch at the server then you can have the page code construct Date instances at the client using the client time zone, but starting from that UTC reference. It's the normal behavior of the Javascript Date() constructor:
var clientDate = new Date(serverUTC);
Now exactly how you get that UTC value depends on your server language. In a JSP page it'd be pretty simple:
var clientDate = new Date(<%= whatever.getTheDate().getTime() %>);
or
var clientDate = new Date(${something.theDate.time});
Once you've got the date value as a client-side Javascript Date instance, you can just update the field(s) with the string. There are no built-in Date formatting tools, but the old standard date.js might help with its ".toString()" formatter.

Categories