get date with timezone javascript - php

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();

Related

PHP strtotime() returns false for JavaScript Date string

At browser,in JS
var today = new Date()
todaySendToServer = today.toString();
I am sending todaySendToServer to server in AJAX call or as part of URL.
At server, in PHP:
$todayJsDateString1 = preg_replace('#^(\d+)/(\d+)/(\d+)\s([\d:]+)\s([a-zA-z]{0,2})$#','$3- $2-$1 $4 $5', $todayJsDateString);
$todayTimestamp = strtotime(todayJsDateString1);
The strtotime() PHP call returns false for date strings returned by some browser(like IE9)
Is there any alternate way to achieve this?
Pass the timestamp instead, so you even don't need to use strtotime in the php side.
var today = new Date();
var ts = today.getTime() / 1000;
It's just a simple typo I guess, you missed a dollar sign:
$todayJsDateString1 = preg_replace('#^(\d+)/(\d+)/(\d+)\s([\d:]+)\s([a-zA-z]{0,2})$#','$3- $2-$1 $4 $5', $todayJsDateString);
$todayTimestamp = strtotime($todayJsDateString1);
Why not send it as a timestamp all the way?
var timestamp = new Date().getTime() / 1000;
$todayTimestamp = $todayJsDateString;

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)

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

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).

>Javascript Comparing 2 dates

I have this code in comparing dates
var startDate = jQuery("#startDate_field_id").val();
var endDate = jQuery("#endDate_field_id").val();
var startDateSplit = startDate.split("-");
var endDateSplit = endDate.split("-");
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
if( end < start ) {
alert("End Date should be less than Start Date of the Event");
}
The value of #startDate_field_id is 2011-10-05
white the value of $endDate_field_id is 2011-10-04
What do you think is the reason why this isn't working.
Any help would be greatly appreciated and rewarded.
Thanks! :)
I think your first problem is that you are using the Date object incorrectly. You are passing three arguments to the setFullYear() method, which only takes a single argument, a 4 digit year.
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
You might want to try something like this:
var start = new Date(startDateSplit[0], startDateSplit[1] - 1, startDateSplit[2])
var end = new Date(endDateSplit[0], endDateSplit[1] - 1, endDateSplit[2]);
I'd use UNIX epoch timestamps for the comparison:
if (end.getTime() > start.getTime()) {
alert('...');
}
Because setFullYear method month parameter accept 0..11, means 9 is October.
why not use
var start = new Date(startDate);
var end = new Date(endDate);
var start = new Date(Number(startDateSplit[0]), Number(startDateSplit[1])-1, Number(startDateSplit[2]));
var end = new Date(Number(endDateSplit[0]), Number(endDateSplit[1])-1, Number(endDateSplit[2]));
or simply:
I am not sure I correctly understand your question .
I guess you want make sure that the end date must be greater than start date.
your code will work fine if you cahnge the if condition .And i just changed the alert message too to get proper meaning
Check this DEMO .

How to turn php time function into javascript function?

I'm not that good at javascript (yet), so I need some help, with an alternative version of this php script (In javascript)
function until($format = ""){
$now = strtotime("now");
$nextTuesday = strtotime("-1 hour next tuesday");
$until = $nextTuesday - $now;
if(empty($format)){
return $until;
}else{
return date("$format",$until);
}
}
Just need it to count down, until next tuesday, in a really short way (Not in 20+ lines, like all the other script I've seen)
It should still return a timestamp, if it's possible (Need it for an offline app)
So if anyone could help me, I would be really happy (Not that I'm not happy right now, but I would be even happier) :D
You may want to take a look at the phpjs site. They have code showing how a substantial number of PHP functions can be done in JS.
Specifically: strtotime and date
JS doesn't have anything remotely close to strtotime. You'd have to determine "next tuesday" yourself. Once you've got that, you can extract a timestamp value using .getTime(), which will be the number of milliseconds since Jan 1/1970. This value can also be fed back into a new date object as a parameter, so you can do date math using simple numbers externally, then create a new date object again using the result.
e.g.
var now = new Date();
var ts = now.getTime();
var next_week = ts + (86400 * 7 * 1000);
next_week_object = new Date(next_week);
Once you've got the "next tuesday" code figured out, the rest is trivial
To get milliseconds till the next tuesday (nearest in the future):
function f_until(){
var now = new Date(Date.now());
var nextT = new Date(Date.now());
var cD = nextT.getDay();
if(cD < 2)nextT.setDate(nextT.getDate() + (2-cD));
else nextT.setDate(nextT.getDate() + (9-cD));
nextT.setHours(nextT.getHours() - 1);
//alert('next tuesday: '+nextT.toString());
return nextT.getTime() - now.getTime();
}

Categories