Convert facebook time zone into my local time zone as facebook does - php

I am using facebook apis and getting created_time as
2012-06-06T16:20:43+0000
I have posted this status at about
21:57 (IST)
and i am getting 2012-06-06T16:20:43+0000
any help will be appreciated, to get the same time as i have posted to get the exact updates.

you can convert any timezone using this code:
$timestamp = strtotime("2012-06-06T16:20:43+0000"); //here you put your string with the tie
$dtime = new DateTime();
$dtime->setTimestamp($timestamp);
$localtz = new DateTimeZone("Asia/Calcutta"); //choose the correct PHP timezone
$dtime->setTimeZone($localtz); //we apply the timezone
$stringtime = $dtime->format('Y-m-d\TH:i:sO'); //here you return the time in the same format as facebook
$unixtime = $dtime->format('U'); //here u get the unix timestamp format of the same string
print $stringtime;

I've written a function earlier for this task,
I've updated it for your needs,
var fbDateFix = function(date){
var local = new Date(date.replace(/-/g,'/').replace('T',' ').replace('+0000',''));
local.setSeconds(local.getSeconds() + 19800);
return local;
}
var padZero = function(t){
if(t<10){
return '0' + t;
}
return t;
}
var d = fbDateFix('2012-06-06T16:20:43+0000');
console.log(d);
var month = padZero(+d.getMonth()+1);
var date = padZero(+d.getDate());
var hour = padZero(+d.getHours());
var min = padZero (+d.getMinutes());
var sec = padZero (+d.getSeconds());
console.log(d.getFullYear() + '-' + month + '-' + date + 'T' + hour + ':' + min + ':' + sec + '+0000')
Edit:
This works for me in php,
date_default_timezone_set('Asia/Calcutta');
$timestamp = strtotime('2012-06-06T16:20:43+0000');
$local_datetime = date('c',$timestamp);
echo $local_datetime;

It looks like the date returned to you is a UTC datetime. You need to convert it to your local timezone (IST)...
See the following SO question for converting datetimes using php:
php convert datetime to UTC

You can use PHP's strtotime to convert created_time to a UNIX timestamp. Then you can add or subtract your time zone offset (IST is UTC+05:30).

Related

Get user timezone string with Javascript / PHP?

I'm trying to get the user's timezone as a string on singup. example:
$timezone = "Asia/Tel_Aviv";
While researching the issue, I got how to Get timezone offset with Javascript, but I'm still unclear about how can I translate the timezone offset to a timezone string in php, as shown above?
Or, which other method cas I use in Javascript / PHP for getting the timezone string for each user?
I'm really not sure how to approach this.
You can't do this in PHP alone.
You can use Javascript to set the value in a cookie, then use PHP to read the cookie on the next page (re)load.
Javascript:
var dateVar = new Date()
var offset = dateVar.getTimezoneOffset();
document.cookie = "offset="+offset;
PHP:
echo $_COOKIE['offset'];
Use this to convert the offset to the friendly timezone name in PHP. Javascript returns the offset in minutes, while this PHP function expects the input to be in seconds - so multiply by 60. The third parameter is a boolean value of whether or not you are in Daylight Savings Time. Read the manual and update the code to fit your needs.
echo timezone_name_from_abbr("", intval($_COOKIE['offset'])*60, 0);
http://php.net/manual/en/function.timezone-name-from-abbr.php
You cannot get the timezone name from an offset. That's because there are many timezones which have the same offset at any given time, so you can't pick one based on an offset. (If you do, this will bite you in the butt later when the timezone goes into or out of DST, changing the offset.
Your best bet is to do geolocation by IP address (google it, lots of material out there) as a best first guess and then give the user an option to choose his timezone himself.
function tzone(){
if(isset($_SESSION["tz"])){ $return = $_SESSION["tz"]; } else {
$ip = $_SERVER["REMOTE_ADDR"];
$getip = file_get_contents("http://freegeoip.net/json/$ip");
$getip = json_decode($getip);
$lat = $getip->latitude; $lng = $getip->longitude; $country = $getip->country_name;
$getzone = file_get_contents("http://api.geonames.org/timezoneJSON?lat=$lat&lng=$lng&username=demo"); //you can change "demo" to your own username. its free service
$getzone = json_decode($getzone);
$zone = $getzone->timezoneId;
$_SESSION["tz"] = $zone;
$return = $_SESSION["tz"];
}
return $return;
}
You need to follow answers of Nicholas Pickering and decezeā™¦ partially. Do not use PHP's timezone_name_from_abbr function(Ref).
Follow these steps to get UTC time of any timezone set in user system:
Javascript (client-side):
var dateVar = new Date();
var offset = dateVar.getTimezoneOffset();
//getTimezoneOffset - returns the timezone difference between UTC and Local Time
document.cookie = "offset="+offset;
Php (server-side):
public function convert_utc_time($date)
{
$time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
if($time_difference != ''){
$time = strtotime($date);
$time = $time + ($time_difference*60); //minutes * 60 seconds
$date = date("Y-m-d H:i:s", $time);
} //on failure of js, default timezone is set as UTC below
return $date;
}
..
..
//in my function
$timezone = 'UTC';
$date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
echo strtotime($date. ' '. $timezone)

get date with timezone javascript

I want to compare date and with date in user timezone after user's login.
I get user's timezone with php.
now How to I take current date/time in javascript of user's timezone current time.
#everyone answered:
I don't need current local system timezone or offset in seconds.
I need users current time with dynamic time I get in php.
For example:
I have 'Asia/Kolkata' or 'America/Denver' or whatever that will be dynamic by php.
Now I can save it to hidden value so that I can get it with Javascript
and than I need current date of this timezone same like Javascript gives date object.
JavaScript uses the system's time zone. You can get the offset via GetTimezoneOffset
<script>
var date=<?php echo date("Y/m/d")?>
</script>
this might help you
Try like this
<script>
var date = '<?php echo date("Y/m/d");?>';
alert(date);
</script>
deeply you can also try like this
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000);
alert(d);
there you can get
Try this:
// date() function
var currDate = new Date()
var n = currDate.getTimezoneOffset();
You can send UTC string
strtotime("2013-02-08 00:00:00");
After that you would have seconsd, that you can convert simple to JS Date:
var utcString = 1360263600 /*AJAX result must be here*/;
new Date(utcString*1000);
You can use Date Object of JavaScript to get user's local system..
for example you can use following:
var d = new Date();
var time = d.getTime();
alert(time);
this will alert the the number of milliseconds since midnight.
You can send this time to your server and compare the both.
For more functions and details you can visit JavaScript Date Object
I am from Taiwan and it returns "+8" for me.
Working example
JS
function timezone() {
var offset = new Date().getTimezoneOffset();
var minutes = Math.abs(offset);
var hours = Math.floor(minutes / 60);
var prefix = offset < 0 ? "+" : "-";
return prefix+hours;
}
$('#result1').html(timezone());
HTML
<div id="result"></div>
Result
+8
I would recommend to use moment.js with moment timezone.
Then you can do something like:
moment().tz("Asia/Kolkata").format();

calculate time difference and display popup based on time difference

im writing a small calendar based on php and jquery which has the a function to calculate the time difference and display a popup 15 minutes before.
Can some one tell me how can i calculate the time difference in minutes and popup 15 minutes before.
my time is saved as
18-07-2012 15:13:54
jsBin demo
var php = '19-07-2012 03:00:00'.split('-');
var phpDate = php[1]+'/'+php[0]+'/'+php[2];
var phpTime = new Date(phpDate).getTime();
var currTime = new Date().getTime();
var difference= phpTime-currTime;
var leftMin = Math.ceil( difference/(1000*60) );
$('#test').text(leftMin+' MINUTES LEFT!');
Code explanation:
To get the remaining time I've done a millisecond comparison of the php returned time in milliseconds from Jan. 1 1970
and the current time in ms from Jan 1 1970 - subtracting the two values and getting the milliseconds difference. To calculate that difference in minutes I've just done:
var leftMin = Math.ceil( difference/(1000*60) );
The trick was to get the right time format and to revert your (php) returned time to that format too.
The default format looks like: MONTH/DAY/YEAR HOURS:MINUTES:SECONDS
To convert the php returned time '19-07-2012 03:00:00'to that one, I used:
var php = '19-07-2012 03:00:00'.split('-'); // split in array fractions
var phpDate = php[1]+'/'+php[0]+'/'+php[2]; // reposition array keys and add '/'
which returns: 07/19/2012 03:00:00 and now we can compare it to the current time e.g.:
07/19/2012 03:45:21
To retrieve the ms from your converted php time we can use:
var phpTime = new Date(phpDate).getTime(); // get "ms from our string
and for the current time we just take:
var currTime = new Date().getTime(); // get "ms from 1/1/1970
Now having our two milliseconds values we can simply subtract them to get the remaining time:
var difference= phpTime-currTime;
Check PHP's DateTime::diff! Maybe it helps you.
var dateStr = '18-07-2012 15:13:54'//Day-Month-Year
var dateArray = dateStr.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateStr2 = '18-07-2012 14:10:54'//Day-Month-Year
var dateArray2 = dateStr2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
-edit; revised code below:-
function timeDiff(date1, date2){
//date format: Day-Month-Year
var dateArray = date1.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateArray2 = date2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
return minutes;
}
if(timeDiff('18-07-2012 15:13:54', '18-07-2012 14:59:54')<=15){
alert('popup')
}
php has an mktime() function (http://php.net/manual/en/function.mktime.php) which takes in a hours, minutes, seconds, month, day, year and calculates the seconds since the epoch (in like 1971). Then you can subtract 15*60 use the date() function to go from seconds back to a date format. (http://php.net/manual/en/function.date.php)

converting date format using javascript

I have a simple textfield with the type defied to be as date which attached with a jquery datepicker(). Now i have set the dateFormat() to be dd-mm-yy. All this works fine. But as i know MySql requires date in yyyy-mm-dd. So i was just wondering if i can convert that date format either using php or javascript to enter into the database.
E.g var date = $('#order_date').val(); gives value 26-2-2012. I need to convert this into 2012-02-26.
Note: There is also a 0 being added to the month.
Use PHP:
$date = $_POST['date']; // e.g. 06-08-2011
$mysql_date = date('Y-m-d', strtotime($date));
or
$date = explode('-', $_POST['date']);
$mysql_date = $date[2].'-'.$date[1].'-'.$date[1];
use $mysql_date to insert into the database.
You can do in javascript by parsing the input and loading it into a Date() object, and then using the getMonth, getDate, and getFullYear functions, as follows:
//Assume input is dd-mm-yyyy
var dateParts = $('#order_date').val().split("-");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
//format using getMonth(), getDate() and getFullYear() methods)
var formattedMonth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var formattedDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var output = date.getFullYear() + '-' + formattedMonth + '-' + formattedDate;
You can see more at this excellent StackOverflow post
did u try date.format("yyyy-mm-dd"); ?
u can also use "isoDate" in place of "yyyy-mm-dd"
and if u are using mysql u can use DATE_FORMAT(date,'%Y-%m-%d')

Want to display the current date/time

Hi I'm using php and sql through odbc to write a program and i hav got abit stuck in a part where i want to display the current date/time in the format date('Y-m-d H:i:s) but it only displays the gmt time. I want to add 8hours to it.Can any of you b able to help me.Thank you so much
Check out date_default_timezone_set. You can do something like:
date_default_timezone_set('America/Los_Angeles');
print 'Current datetime is: ' . date('Y-m-d H:i:s');
You could use that to set the timezone to whatever timezone you need time to be at, and then use date normally. Alternatively, you can do this, using strtotime:
print 'Current datetime is: ' date('Y-m-d H:i:s', strtotime('+8 hours'));
If you're looking for a way to display a timestamp in a user's local time, you can use JavaScript:
function showtime(t)
{
if (t == 0)
{
document.write("never");
return;
}
var currentTime = new Date(t);
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
document.write();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
document.write(month + "/" + day + "/" + year + " " +
hours + ":" + minutes + ":" + seconds + " ");
if(hours > 11){
document.write("PM");
} else {
document.write("AM");
}
}
Then if you need to display a time, just make a call to it in the HTML and splice in the value from PHP:
<script type="text/javascript">showtime(<?=$time."000"?>)</script>
I would steer clear of the timezone method.
If i understood correctly, you want to add time, thus change it. An example could be, A task has been created NOW, and must be complete in 8 hours. The timezone method would only change the display of the date and time. Only change the timezone setting if you know your visitor's timezone, and datetime's must be shown relative to them.
Now: 1234418228 is 2009/02/12 00:57:08 in Montreal or 2009/02/11 09:57:08 in San Francisco. It's the exact same moment.
Appending to the first answer, date() and strtotime() are your friends.
strtotime( "+8 hours", $now )
$now being a timestamp of when it's supposed to relate to. So if your start time isn't time(), you can still use that. eg
strtotime( "+8 hours", strtotime( "2009/03/01 00:00:00" ); (8AM on 2009/03/01)
However, when dealing with intervals counted in weeks, or less, i prefer doing it 'mathematically'
$StartTime = strtotime( "2009/03/01 13:00:00" );
$EndTime = $StartTime + ( 8 * 60 * 60 );
date( "Y/m/d H:i:s", $EndTime ) ==> "2009/03/01 21:00:00"
3600 seconds in an hour, 86400 in a day.
You can't use this method for months, quarters or years because the number of seconds they last varies from one to the next.
If you want to use time for a certain timezone, then using date_default_timezone_set() is preferred. anyway you can provide the date() function another parmater: int timestamp. an integer representing the timestamp you would like date() to return the information about.
so if you would like to show date('Y-m-d H:i:s') for now you can use this:
$now = date('Y-m-d H:i:s', time() ); // time() returns current timestamp.
// if you omit the second parameter of date(), it will use current timestamp
// by default.
$_8hoursLater = date('Y-m-d H:i:s', time()+60*60*8 );
$_8hoursBefore = date('Y-m-d H:i:s', time()-60*60*8 );

Categories