Detecting DataTimeZone - javascript

I would like to automatically detect visitors timezone so the date and time displayed reflects their current time. I realize this isn't possible with PHP alone but will need some JavaScript as well.
What can I use to replace the value of $timezone in the code below to automatically detect a visitors timezone?
<?php
// Date & time format.
$date_format = "m/d/Y";
$time_format = "h:i A";
$timezone = "America/New_York";
// Get current datetime.
$date = new DateTime();
// Set timezone.
$date->setTimezone(new DateTimeZone($timezone));
// Echo current date and time.
echo $date->format($date_format . " " . $time_format);
?>
Returns:
07/22/2014 03:03 PM

Using java script you can use it
<script src='http://code.jquery.com/jquery-2.1.1.js'></script>
<script src="https://bitbucket.org/pellepim/jstimezonedetect/raw/f9e3e30e1e1f53dd27cd0f73eb51a7e7caf7b378/jstz.min.js"></script>
<script>
$(document).ready(function(){
var timezone = jstz.determine();
$("#div").html(timezone.name());
});
</script>
<div id='div'></div>
Remember that download jstz.min.js it doesn't allow embed from https://bitbucket.org/
if you want see it working giv one look at
http://gomusic.designerbh.com/teste.php

It would be best to use Javascript
See this fiddle for an example
jQuery(document).ready(function() {
var foo = jQuery('#foo');
function updateTime() {
var now = new Date(),
d = [];
d[0] = now.getFullYear().toString(),
d[1] = now.getMonth()+1, //months are 0-based
d[2] = now.getDate(),
d[3] = now.getHours(),
d[4] = now.getMinutes();
//doing YY manually as getYear() is deprecated
//remove the next line if you want YYYY instead of YY
d[0] = d[0].substring(d[0].length-2); //not using substr(-2) as it doesn't work in IE
//leading zeroes
for (var i=1; i<=4; i++)
if (d[i] < 10) d[i] = '0' + d[i];
foo.val(d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4]);
}
updateTime();
setInterval(updateTime, 5000); // 5 * 1000 miliseconds
});

Related

How can I use input type date to dynamically only allow for one year from current date?

Here is my code so far. I am not sure how to accomplish a max date other than setting that in the input tag itself. I want it to be dynamic so whatever the current date is, the calendar only allows a selection of up to one year.
<input type="date" id="txtDate" />
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = dtToday + 365;
alert(maxDate);
$('#txtDate').attr('max', maxDate);
});
example: today is 10/1/2019 it should be allowed to only select dated from 10/1/2019-10/1/2020 tomorrow a user should be allowed to only select from 10/2/2019-10/2/2020
link to fiddle
Setting the min and max values for a date input based on today's date can be done when the page loads:
// Formt date as YYYY-MM-DD
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
window.onload = function() {
let inp = document.querySelector('#i0');
let d = new Date();
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() + 1);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
<input type="date" id="i0">
If the user agent doesn't support input type date, this will still set the min/max/default values, but you'll have to handle out of range values yourself.
Just add a year to the current date
var dtToday = new Date();
dtToday.setYear(dtToday.getYear() + 1);
$(function(){
var dtToday = new Date();
dtToday.setFullYear(dtToday.getFullYear() + 1)
let formatted_date = dtToday.getFullYear() + "-" + (dtToday.getMonth() + 1) + "-" + dtToday.getDate()
alert(formatted_date);
$('#txtDate').attr('max', formatted_date);
});
You can't add to a date object like that; you need to first get it as a timestamp. You can do that by using Date.now() or, if you need the Date object, dtToday.getTime().
That gives you a timestamp in milliseconds, so you also need to convert 365 days into milliseconds; meaning you want to add 365 * 24 * 60 * 60 * 1000 to it, not just 365.

PHP: strtotime not work from file_get_contents

Hello i try to convert date to strtotime but my code not work;
time.html - show current time like 2017-03-09 07:11:01
time.html
<script type="text/javascript">
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
var month = '0' + month;
}
if(day.toString().length == 1) {
var day = '0' + day;
}
if(hour.toString().length == 1) {
var hour = '0' + hour;
}
if(minute.toString().length == 1) {
var minute = '0' + minute;
}
if(second.toString().length == 1) {
var second = '0' + second;
}
var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
}
document.write(getDateTime());
</script>
index.php
$file = file_get_contents("http://localhost/time.html");
$file = strtotime($file);
echo "Time: ". $file;
code work like this: strtotime("2017-03-09 07:11:01"); but i need with file_get_contents to get real time (current time), thanks in advance
javascript is client-side, so you cant get it from php, time.html will only print the date when a user reads it (will show the user time). If you want print the time in php you should use the php function date(), so you will get the server date (php is server-side), for example:
echo "Time: ". date("Y/m/d H:i:s");
Note: strtotime() is a function to check or convert a string to time format

JavaScript date to MySQL datetime conversion

I have a js date variable
var date = "2017-01-23T10:17:50.285Z";
I have stored this in MySQL table and the column have type DATETIME
after storing in the database the value in the table looks like this:
Now when I am trying to get the record from the database using this column name I am doing like this:
var mysqlFormate = new Date(date).toISOString().slice(0, 19).replace('T', ' ');
which is giving the output as 2017-01-23 10:17:50
The problem
You can see the value stored in the database is different than the converted value (2017-01-23 15:47:50 and 2017-01-23 10:17:50 are different).
So I am not able to get the data from the database using this column.
What can be the possible mistake I am doing here? Thanks.
Check How you could set Time Zone information on SQL Server(or follow a convention).
in
new Date(date).toISOString().slice(0, 19).replace('T', ' ')
Replace the toISOString with formatLocalDate() with the below definition
function formatLocalDate() {
var now = new Date(),
tzo = -now.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '-' + pad(now.getMonth()+1)
+ '-' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ ':' + pad(now.getMinutes())
+ ':' + pad(now.getSeconds())
+ dif + pad(tzo / 60)
+ ':' + pad(tzo % 60);
}
there's a clear 5h30m so I presume you're converting(or forgetting) the GMT to IST Offset.
In order to show the local time in JS there is Date.UTC() function it tells the browser that the date you're about to give it is expressed in UTC, that way, the browser will apply the required conversion and show it as local time.
function getLocalTime(mysqlDate) {
var dateTime = mysqlDate.split(' ');
var date = dateTime[0].split('-');
var time = dateTime[1].split(':');
var utc = Date.UTC(date[0], date[1], date[2], time[0], time[1], time[2]);
return new Date(utc);
}

Is there a reliable way to convert a naive UTC time stamp to local time with javascript?

Determining a user's timezone server side and converting from UTC has proven more trouble than its worth.
Is there a reliable way for javascript/jquery to determine the timezone of the user and apply the offset to a UTC datetime stamp (2012-08-25 10:59:56.511479) and output in my desired format (Aug 25 '12 - 10:59AM)?
What might the jquery code look like to say
// dom ready
$('span.localtime').each(function(e) {
// get stamp and apply conversion
});
.getTimezoneOffset() is available on the date object, and gives you the offset from UTC in minutes.
var offset = (new Date()).getTimezoneOffset();
// convert myUtcDate to a date in local time
myUtcDate.setMinutes(myUtcDate.getMinutes() + (offset*-1));
Thus:
$('.span.localtime').each(function() {
var myUtcDate = new Date($(this).html()); // assuming "2012-08-25 10:59:56.511479"
myUtcDate.setMinutes(myUtcDate.getMinutes() + (myUtcDate.getTimezoneOffset() * -1));
$(this).html(myUtcDate.toString());
});
Note that myUtcDate.toString() could be replaced with any date formatting you want. In your case, it might look like
$(this).html(formatDate(myUtcDate));
function formatDate(d) {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var y = d.getFullYear().toString().slice(-2); // "12"
var m = months[d.getMonth()]; // "Aug"
var d = d.getDate(); // "25"
var ampm = 'AM';
var h = d.getHours();
if(h>=12) {
h -= 12;
ampm = 'PM';
}
if(h == 0)
h = 12;
var min = ("00" + d.getMinutes()).slice(-2);
return m + " " + d + " '" + y + " - " + h + ":" + min + ampm;
}
You might want to use a date format plugin for formatting dates in a neater more reliable manner.
Also, have a look at https://github.com/GregDThomas/jquery-localtime - it wraps all this up in a simple to use jQuery plugin.

Change dates inside span to match user's timezone

I have this function:
function get_time_zone_offset() {
var current_date = new Date();
return -current_date.getTimezoneOffset() / 60;
}
I want a jQuery code to change every span which class is 'timeago' title value to its value plus the number the function above returns. For example:
Before:
<span class="timeago" title="7/4/2012 9:28:30 AM">7/4/2012 9:28:30 AM</span>
After:
<span class="timeago" title="7/4/2012 12:28:30 PM">7/4/2012 12:28:30 PM</span>
Assuming 7/4/2012 9:28:30 AM represents UTC, you can let the Date object do all the math:
function formatDate(d) {
var yy = d.getFullYear();
var mm = d.getMonth() + 1;
var dd = d.getDate();
var hh = d.getHours();
var ii = d.getMinutes();
var ss = d.getSeconds();
var ap;
if (hh < 12) {
if (hh === 0) {
hh = 12;
}
ap = "AM";
}
else {
if (hh > 12) {
hh -= 12;
}
ap = "PM";
}
return mm + "/" + dd + "/" + yy + " " + hh + ":" + ii + ":" + ss + " " + ap;
}
$("span.timeago").each(function() {
var dateInput = $(this).text();
var dateInUTC = new Date(dateInput + " +0000"); // note: +0000 is the key
var dateOutput = formatDate(dateInUTC);
$(this).attr("title", dateOutput).text(dateOutput);
});
This assumes that the date is parsable. Here is a demo.
It seems a simple loop like this should work:
$('span.timeago').each(function(index, elm) {
var newVal = $(elm).attr('title') * 1 + get_time_zone_offset(); // multiply by 1 to suppress string concatenation
$(elm).attr('title', newVal);
});
It's pretty straightforward by passing a function to .attr [docs]:
var offset = get_time_zone_offset();
$('span.timeago').attr('title', function(i, val) {
return +val + offset;
});
If you have to convert the value to a proper timestamp first, have a look at How to convert from date to unix_timestamp using javascript.
If you are using the Timeago plugin, note this remark:
Are you concerned about time zone support? Don't be. Timeago handles this too. As long as your timestamps are in ISO 8601 format and include a full time zone designator (±hhmm), everything should work out of the box regardless of the time zone that your visitors live in.
So you might not even have to do this conversion manually. Just add the proper timezone information to values.

Categories

Resources