In PHP I have used below code to get the time of US.
date_default_timezone_set('UTC');
$dateTimeZoneLA = new DateTimeZone("America/Los_Angeles");
$dateTimeLA = new DateTime("now", $dateTimeZoneLA);
Now I need to add validation of datetime using jQUery but how can I match the US time with the calender time. time using jQUery. Below is the code I have used in jQuery. But it did not workk acc. to US time.
var starttime = $('#dateTime').val();
var present = new Date(now);
var firstDate = new Date(starttime);
if(present.getTime() > firstDate.getTime()){
$('#dateTime').after('`<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>`');
}
Related
I would like to print the time in local time in Laravel. If the user create a post it will display the created time on the server. How can I display it in local time ?
In my blade file I used this code to display created time,
{{{ $posts->updated_at }}}
Which displays the time in database, which is a server time. How can I convert it to users local time ?
I found a solution to convert time to local time by using session. The current time zone offset will store on session to calculate users time. Create a jquery post function to post users timezone offset to session. This is my code,
default.blade.php
#if($current_time_zone=Session::get('current_time_zone'))#endif
<input type="hidden" id="hd_current_time_zone" value="{{{$current_time_zone}}}">
// For assigning session value to hidden field.
<script type="text/javascript">
$(document).ready(function(){
if($('#hd_current_time_zone').val() ==""){ // Check for hidden field is empty. if is it empty only execute the post function
var current_date = new Date();
curent_zone = -current_date.getTimezoneOffset() * 60;
var token = "{{csrf_token()}}";
$.ajax({
method: "POST",
url: "{{URL::to('ajax/set_current_time_zone/')}}",
data: { '_token':token, curent_zone: curent_zone }
}).done(function( data ){
});
}
});
routes.php
Route::post('ajax/set_current_time_zone', array('as' => 'ajaxsetcurrenttimezone','uses' => 'HomeController#setCurrentTimeZone'));
HomeController.php
public function setCurrentTimeZone(){ //To set the current timezone offset in session
$input = Input::all();
if(!empty($input)){
$current_time_zone = Input::get('curent_zone');
Session::put('current_time_zone', $current_time_zone);
}
}
Helpers/helper.php
function niceShort($attr) {
if(Session::has('current_time_zone')){
$current_time_zone = Session::get('current_time_zone');
$utc = strtotime($attr)-date('Z'); // Convert the time zone to GMT 0. If the server time is what ever no problem.
$attr = $utc+$current_time_zone; // Convert the time to local time
$attr = date("Y-m-d H:i:s", $attr);
}
return attr;
}
index.blade.php
{{ niceShort($posts->updated_at) }}
Now we can print the time in clients time zone. The time zone setting code run only when the session empty.
You can do this by using javascript. Use following libraries:
moment.min.js (http://momentjs.com/downloads/moment.js)
moment-timezone-with-data.js ()
jstz.min.js (https://bitbucket.org/pellepim/jstimezonedetect)
Here is the code :
var update_at = '<?php echo $posts->updated_at;?>'; //set js variable for updated_at
var serverTimezone = 'YOUR SERVER TIME ZONE'; //set js variable for server timezone
var momentJsTimeObj = moment.tz(update_at, serverTimezone); //create moment js time object for server time
var localTimeZone = jstz.determine(); //this will fetch user's timezone
var localTime = momentJsTimeObj.clone().tz(localTimeZone.name()).format(); //convert server time to local time of user
Now you can display local time through js
Try this method, I think this is what you want:
$localTime = $object->created_at->timezone($this->auth->user()->timezone);
Here, $this->auth->user()->timezone will return current user's timezone, and timezone() will convert created_at to to user's local time.
If you want to get all visitors timezone (not just logged in users), you can you package for Laravel similar to laravel-geoip. It will generate $visitor['timezone'] for you which you can use like this:
$localTime = $object->created_at->timezone($visitor['timezone']);
Best option is to do this with Javascript, get client's timezone and then convert server time to cleint's accordingly.
Please refer https://stackoverflow.com/a/1837243/4007628
Try this:
$dt = new DateTime($posts->updated_at);
$tz = new DateTimeZone('Asia/Kolkata'); // or whatever zone you're after
$dt->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s');
Go to app.php page in Config folder and change this
'timezone' => 'UTC',
to
'timezone' => 'addYourTimeZoneHere',
reference
https://laravel.com/docs/5.5/configuration
find your timezone
http://php.net/manual/en/timezones.php
Server time should stick with UTC timezone
In front end, you can use moment.js to render the correct local timezone. I tested this in moment version 2.22.2.
Simply add Z to the datetime value and moment will render the date to user's local time zone
moment(dateTimeValue + ' Z');
Comment the timezone settings in app.php page
//'timezone' => 'UTC',
With jQuery's $.post i want to send a value to my php function , where inside it should lookup the events by it's current selected month.
Now there some programmatic problems.
First is to what value it is best to make the check against.
In theory i have all available, but the ideas i have all seem to be clumsy.
If it helps , i use the following script that does all the calculation with the data i provide it with. eventCalendar
For my testing purposes , just to make a check if the event is active or not i use the following code:
var Calendar = new Object();
Calendar.id = '1';//Check if active 1 or 0
var calendarJson = JSON.stringify(Calendar);
$('#indicator').show();
$.post('Controller.php',
{
action: 'get_events',
calendar: calendarJson
},
function(data, textStatus) {
....more code
Were the data is retrieved and handled as:
public function getEvents($calendar){
$sth = $this->dbh->prepare("SELECT * FROM events WHERE current = ?");
$sth->execute(array($calendar->id));
return json_encode($sth->fetchAll());
}
Where in the counted result the most important data = event_sdate varchar(255)
looks like:
event_sdate = 1394220775280 (milliseconds)
However my intention is to let it send back all events by it's given month.
So i have to replace current = ? with something that is inserted when create a new event.
And that should, at least it is what i think, the month and year of creation.
And when make the call to the php function:
Calendar.id = '1';//Check if active 1 or 0
Should be something like:
Calendar.id = 'March 2014';//Check if current month and year
When i load the calendar without any events yet it looks like:
this jsfiddle
I hope someone could point me in the right direction of how to achieve what i try to do
It seems i answered my own question.
Should be something like:
Calendar.id = 'March 2014';//Check if current month and year
Generated HTML contains required values:
<div id="eventCalendarInline" data-current-year="2014" data-current-month="2">
in jQuery:
var currentYear= $('#eventCalendarInline').data("current-year");
var currentMonth = $('#eventCalendarInline').data("current-month");
var Calendar = new Object();
Calendar.month = currentMonth;
Calendar.year = currentYear;
And in php:
public function getEvents($calendar){
$sth = $this->dbh->prepare("SELECT * FROM events WHERE cyear = ? AND cmonth = ?");
$sth->execute(array($calendar->year, $calendar->month));
return json_encode($sth->fetchAll());
}
So here's what I'm trying to do - I have the following code:
<div id="on">
<p>We are: <span class="onair">ON AIR</span></p>
</div>
<div id="off">
<p>We are: <span class="offair">OFF AIR</span></p>
</div>
And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.
?
If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.
(Client side solutions work too if you dont care about where the time is coming from)
(1) You can have the server render javascript for you that you can use in a script
//if you want the server's time you can do this:
<?php $timestamp = time(); ?>
//render variables in javascript instead of html
<?php
echo <<<EOD
<script>
var timestamp = ${timestamp}
//then later in your javascript process the timestamp logic to update the dom
</script>
EOD;
?>
(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)
//onAirClass( min, max, timestamp ) returns className
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
if( timestamp >= timeMin && timestamp <= timeMax ){
return 'onair';
}
return 'offair'
}
//using onAirClass( min, max, timestamp )
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>
then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.
Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function
How to check the time between a given time range
UPDATED
Corrected PHP syntax errors
#maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:
var timestamp = $('#server-timestamp').text();
Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.
There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:
is simple
is efficient (doesnt do anything unnecessary or redundant)
falls in line with best practices
Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.
Here's a function you can use:
var onAir = function (day, start, end, timezone) {
var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;
// by default, we are not on air
onAir = false;
// map day numbers to indexes
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];
// convert start/end times to date objects
startValues = start.split(':');
endValues = end.split(':');
startTime = new Date();
endTime = new Date();
startTime.setHours(startValues[0], startValues[1]);
endTime.setHours(endValues[0], endValues[1]);
// add the hours minutes together to get total minutes
startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();
// get the current local time
local = new Date();
// get the current time in the show's timezone
utc = local.getTime() + (local.getTimezoneOffset() * 60000);
show = new Date(utc + (3600000*timezone));
// convert the show hours + minutes to just minutes
showMinutes = (show.getHours() * 60) + show.getMinutes();
// test to see if the show is going on right now
if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
onAir = true;
}
return onAir;
}
// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));
// now check if we are on air
if (texasShowOnAir) {
// do stuff here...
}
You can now use this function like this:
var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');
This will return a true/false. Be sure and use 24 hour format.
I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.
Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/
Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.
Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.
From the server:
<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>
On the client:
$(document).on('load', function() {
var serverTime = new Date($('#server-timestamp').text())
, clientTime = new Date()
, offsetMilliseconds = (clientTime - serverTime);
setInterval(function() {
// If server time is 3pm-4pm then hide/show divs...
}, 1000 /* every second */);
});
I have a quiz page with some questions (multiple choice, true-false). In the results after the submit of page i want to show something like this:
Started on Tuesday, 1 January 2013, 04:09 AM
Completed on Tuesday, 1 January 2013, 04:10 AM
Time taken 47 secs
Grade 7 out of a maximum of 10 (65%)
i dont know how to count start time and end time to show the above results and how to count the time from when user's load a page until they submit the form.
i'm new and i need your advise. i dont have problem if the problem solved with php or javascript or jquery
You can do something like this and the start and end timestamps will be submitted along with the form. You could then do the calculations with PHP.
var form = document.getElementById("form");
window.onload = function() {
var start = document.createElement("input");
start.type = "hidden";
start.name = "start";
start.value = +new Date()/1000; //unix timestamp
form.appendChild(start);
};
form.onsubmit = function() {
var stop = document.createElement("input");
stop.type = "hidden";
stop.name = "stop";
stop.value = +new Date()/1000;
form.appendChild(stop);
};
Ok here is my solution:
1- user starts the quiz and you put the time in $_SESSION var
$_SESSION['quiztime']=date("Y-m-d H:i:s");
2-User finishes the test and you check the time passed (this example is in minutes you don't have to divide it by 60 if you need seconds)
$to_time = strtotime(date("Y-m-d H:i:s"));
$from_time = strtotime($_SESSION['quiztime']);
echo round(abs($to_time - $from_time) / 60,2). " minutes";
I'd put the time started in a cookie or session, and then once they complete it, just subtract that time from the current time -- That's the time taken!
It may look like this:
Quiz page:
session_start();
$_SESSION['startTime'] = time();
// This is where the quiz would be displayed
Quiz results page:
session_start();
$totalTime = time() - $_SESSION['startTime'];
echo $totalTime;
My "bullet-proofer" solution would be to store the start time on the server, (in the session) associated with a unique id generated per-form and kept in an hidden field.
This way you prevent the user from tampering with it (he might change the unique id, but in that case the form would be invalid) and you don't depend on the client having javascript enabled.
<?php
$form_uuid = uniqid();
$_SESSION['quiz_start_time'][$form_uuid] = time();
Then, in your form, put something like this:
<input type="hidden" name="form_id" value="<?php print $form_uuid; ?>">
And in the form submit handler:
<?php
$form_uuid = $_POST['form_id'];
if (!isset($_SESSION['quiz_start_time'][$form_uuid])) {
// The user is trying to do something nasty (or the session just expired)
// Return something like a 400 error
}
else {
$start_time = $_SESSION['quiz_start_time'][$form_uuid];
// Do other form processing here..
}
I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client