Get current timezone in Twig - php

Is there any way to get current timezone in Twig templates rather than passing from crontroller. This link gives the date for a specific timezone.
{{ post.published_at|date("m/d/Y", "Europe/Paris") }}

Maybe you could try a JS solution, like moment.js. You can assign a special CSS class (eg. date-transform) and run a script on all elements with this class:
$('.date-transform').each(function(){
var initialDate = moment($(this).html(), 'MMMM D, YYYY HH:mm');
if (initialDate.isValid()) {
var offset = moment().utcOffset(); // this is the client UTC offset
var finalDate = initialDate.add(offset, 'minutes').format('MMMM D, YYYY HH:mm');
$(this).html(finalDate);
}
});

Related

Formatting database date to AM/PM time (vue)

I'm receiving dates from my database in the format 2018-08-08 15:38:48 however I want it to show 3:38 pm instead.
I'm just unsure when to make this change, can I change it while it is being posted? They are dates of messages being sent to a person.
Current code:
<div v-for="messages in userMessages">
<div class="date">
{{ user.created_at }}
</div>
</div>
Output:
2018-08-08 15:38:48
How do I transform the date in vue? (when it is in a v-for?)
Vue does not offer date formatting. You will need your own filter to format the date. Or you use a package like the following: https://github.com/brockpetrie/vue-moment#readme
<span>{{ someDate | moment("hh:mm a") }}</span>
Vue.js does not natively allow dates to be formatted in a different way.
I suggest you to use more famous libraries like moment.js to format your dates however you want.
For example:
import moment from 'moment'
Vue.filter('formatDate', function(value) {
if (value) {
return moment(String(value)).format('MM/DD/YYYY hh:mm')
}
}
https://momentjs.com/
How do you use it?
You can use like this.
moment('2018-08-08 15:38:48').format('LTS'); // 03:38:48 PM
Your datetime format is not the ISO standard we would like, but we'll live with it... When handling dates, it's a good practice to convert them to date objects as soon as you receive them. If they're arriving in JSON, you can do this with a reviver function as the second argument to JSON.parse(). Here is a reviver function that will do the job for you...
Then,at the point you need to display, you can format your time with toLocaleTimeString()
function nReviver(key, value) {
var a;
if (typeof value === "string") {
a = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d*)?$/.exec(value);
if (a) {
return new Date(a[0]);
}
}
return value;
}
// do this when you receive your data from the server and all
// dates, wherever they are in the JSON, will be converted to date objects
var myObj = JSON.parse('{"myDate":"2018-08-08 15:38:48"}',nReviver)
// ...then, when you want to display, format with toLocaleTimeString()
console.log(
myObj.myDate.toLocaleTimeString({},{
hour12:true,
hour:'numeric',
minute:'numeric'
})
.toLowerCase()
)

How to get the selected date and time from bootstrap datetimepicker [duplicate]

I need to get the value of Datetimepicker in my JavaScript function. I have made something like this, but it doesn't work:
$("#date").click( function(){
alert(document.getElementById('datetimepicker1').value);
});
It gives me 'undefined'
Either use:
$("#datetimepicker1").data("datetimepicker").getDate();
Or (from looking at the page source):
$("#datetimepicker1").find("input").val();
The returned value will be a Date (for the first example above), so you need to format it yourself:
var date = $("#datetimepicker1").data("datetimepicker").getDate(),
formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours + ":" + date.getMinutes() + ":" + date.getSeconds();
alert(formatted);
Also, you could just set the format as an attribute:
<div id="datetimepicker1" class="date">
<input data-format="yyyy-MM-dd hh:mm:ss" type="text"></input>
</div>
and you could use the $("#datetimepicker1").find("input").val();
It seems the doc evolved.
One should now use :
$("#datetimepicker1").data("DateTimePicker").date().
NB : Doing so return a Moment object, not a Date object
To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:
$('#datetimepicker').data("DateTimePicker").FUNCTION()
So you can try the function:
$('#datetimepicker').data("DateTimePicker").date();
Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/
Or try:
$("#datetimepicker").data().date;
Since the return value has changed, $("#datetimepicker1").data("DateTimePicker").date() actually returns a moment object as Alexandre Bourlier stated:
It seems the doc evolved.
One should now use : $("#datetimepicker1").data("DateTimePicker").date().
NB : Doing so return a Moment object, not a Date object
Therefore, we must use .toDate() to change this statement to a date as such:
$("#datetimepicker1").data("DateTimePicker").date().toDate();
I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)
This is how you should use DateTime Picker inline:
var selectedDate = $("#datetimepicker").find(".active").data("day");
The above returned: 03/23/2017
This is working for me using this Bootsrap Datetimepiker, it returns the value as it is shown in the datepicker input, e.g. 2019-04-11
$('#myDateTimePicker').on('click,focusout', function (){
var myDate = $("#myDateTimePicker").val();
//console.log(myDate);
//alert(myDate);
});
I tried all the above methods and I did not get the value properly in the same format, then I found this.
$("#datetimepicker1").find("input")[1].value;
The above code will return the value in the same format as in the datetime picker.
This may help you guys in the future.
Hope this was helpful..

How to convert server time to local time in Laravel?

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',

PHP JS Transform date to user timezone

I have a page that shows future events along with the date (server time).
I need some method to display the date in user time.
Example:
Oct, 26 13:48:23 (server)
Oct, 26 14:48:23 (user time (UTC +1)) -> event info
What I have so far:
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo date('M, d H:i:s', strtotime ($row['date'])).' -> '.$row['info'];
}
?>
With the diffence I want to detect user timezone.
Thank you.
EDIT
I know I should not be using mysql_*
If you're ok with doing the conversion to the user's time zone in JavaScript, you could do the following:
PHP
<?php
$sql=mysql_query("SELECT * FROM table") or die("Come back later");
while($row=mysql_fetch_array($sql)) {
echo '<span class="date">' . date('M, d H:i:s', strtotime ($row['date'])) . ' UTC</span> -> '.$row['info'];
}
?>
JavaScript (With jQuery for Readability)
$(function(){
$('.date').each(function(){
var $this = $(this);
// Parse the date string (the format you've given will
// work, and the added UTC above will give JavaScript
// some context)
var dateVal = new Date($this.text());
// JavaScript will convert it to the user's timezone when
// stringifying it (helped by the server timezone specified
// in the PHP.
$this.text(dateVal.toString());
});
});
If you want to render the dates in the format: Oct, 26 13:48:23, you could do this:
var dateString = dateVal.toLocaleString();
var parts = /^\w+ (\w+ \d{1,2}) \d{4} (\d{2}:\d{2}:\d{2})/.exec(dateString);
dateString = parts[1] + ' ' + parts[2];
Then use $this.text(dateString); to inject it into the dom.
You need to create DateTime object from this date, and then apply DateTimeZone to that object.
You would need to get the timezone from the user.
You can accomplish this by offering a dropdown with timezones that the user can select and submit. To make this a little more user friendly you could use some of the geoip functions to detect country and region and then determine a default timezone for the user. Do keep in my that location by IP is not 100% accurate but is instead an educated guess as to where the user may be located.
Alternatively you can use ajax to send the timezone to the server and then update accordingly.

JQuery and PHP Date difference

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

Categories