code igniter date helper in not working for me. I initialized the date helper and while inserting in database. I see that field with timestamp are returning 0000-00-00 . Code for insertion is:
function add_todo($list)
{
date_default_timezone_set("Asia/kathmandu");
$date = now();
$data = array(
'list' => $list,
'dates'=> now()
);
$insert = $this->db->insert('todo', $data);
}
I cannot get is working. What is the problem here.
Id imagine its not working because you don't have the correct configuration.
This is from the codeigniter wiki for the now() function:
Returns the current time as a Unix timestamp, referenced either to your server's local time or GMT, based on the "time reference" setting in your config file. If you do not intend to set your master time reference to GMT (which you'll typically do if you run a site that lets each user set their own timezone settings) there is no benefit to using this function over PHP's time() function.
try using this
$datetime = date('Y-m-d H:i:s');
This would be revised code but I'm not at a machine were i can test it. However, this should work..
function add_todo($list)
{
date_default_timezone_set("Asia/kathmandu");
$datetime = date('Y-m-d H:i:s');
$data = array(
'list' => $list,
'dates'=> $datetime
);
$insert = $this->db->insert('todo', $data);
}
You can try out this
date_default_timezone_set('Asia/Kathmandu');
$dateTime = date('Y-m-d H:i:s');
$data = array(
'date'=> $datetime
);
$insert = $this->db->insert('todo', $data);
Related
I have changed my DB version MariaDB to MySQL but my date format is not working properly and showing always 01-01-1970. How can I get rid of this ?
before conversion of DB it was working fine. what should I need more to do ?
I am working on codeignitor with this query. Please check .
$created = $this->Common_model->getAllData('certificate_master', 'created', true, ['id' => $lastId])->created;
$timestamp = strtotime($created);
$createdNew = date('d-m-Y', $timestamp);
$createdNew is always returning 01-01-1970.
Thanks in advance.
I have solved my issue. Actually here when we are creating last inserted id it was going to work after delay with some seconds so I used function sleep() for three seconds delay like sleep(3) after generation of $lastId;
$lastId = $this->db->insert_id();
sleep(3);
$created = $this->Common_model->getAllData('certificate_master', 'created', true, ['id' => $lastId])->created;
$timestamp = strtotime($created);
$createdNew = date('d-m-Y', $timestamp);
So I already save any date on my database with UTC, and I can get it just like $data->created_at or $data->blocked_at. So in my config, I set timezone to UTC, then i want to convert when on view from UTC to UTC+7 or another timezone.
Is there an easy way to convert timezone i want when on view for all dates?
I'm still using Laravel 5.8
Edit:
I'm using the answer but implement that on my base model, like this:
public function getDateConverter($key){
if(strtotime($this->{$key})){
$date = Carbon::createFromFormat('Y-m-d H:i:s', $this->{$key});
$date->setTimezone(env("APP_TIMEZONE_VIEW"));
return $date->toDateTimeString();
} else {
return null;
}
}
And I will call the column name like this $data->getDateConverter("created_at");
You can use Carbon which is included in the core
$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');
Europe/Stockholm is your default timezone and UTC is what you want to set
If you want to convert it from a model when displaying, try Accessors
public function getCreatedAtAttribute($value)
{
$date = Carbon::createFromFormat('Y-m-d H:i:s', $value, 'Europe/Stockholm');
$date->setTimezone('UTC');
return $date->toDateTimeString();
}
well in case if you want to chnage your timezone when inserting the time then
Use 'timezone' => 'Asia/Kolkata'. in your config/app.php
By this you can set your applications default timezone..
you can use add this function to your model
public function setViewDateFormat( $date ) {
return Carbon::parse( $date ,'Africa/Cairo')->format( 'j F Y' );
}
Then call it on any date attribute
public function getFormattedCreatedAtAttribute() {
return ( $this->created_at ) ? $this->setViewDateFormat( $this->created_at ) : null;
}
This way you can set all dates timezone and format.
What I want is to make a database update with codeigniter where I put a value to current timestamp:
My settings array:
$settingsMachineUpdateEvent[] = array(
'id' => $eventId,
'etid' => '5',
'insert_by' => '2',
'modified_date' => $currentTime
);
And my $currentTime:
$currentTime = date_default_timezone_get();
And I send the update like this:
$this->db->update_batch('balance_events', $settingsMachineUpdateEvent, 'id');
My problem is the $currentTime var, I want to assign it the current time stamp so I can update my modified_date column from mysql with the current timestamp value. I also try'ed with NOW(), time(), and assign it directly from array, nothing worked, I will get 0000-00-00 00:00:00 after the update. Where is the issue? Thanks!
Instead of this:
$currentTime = date_default_timezone_get();
try
$currentTime = date('Y-m-d H:i:s'); // for current time
$currentTime = time(); // for current timestamp
Explanation: date_default_timezone_get() is used to get the timezone, but in your case you need the time or timestamp to store in the table.
I'm trying to store user signup date and time using codeigniter 3.0.6 and using
NOW()
as
$this->db->set('user_nicename', $nameVar);
$this->db->set('user_login', $emailVar);
$this->db->set('user_pass', $passwordVar);
$this->db->set('user_registered', 'NOW()');
$this->db->insert('doc_users');
but it is not storing date time in database
see database image
use date() like this
date('Y-m-d H:i:s'); # output 2015-12-22 16:41:25
Final Code is
date_default_timezone_set('Asia/Karachi'); # add your city to set local time zone
$now = date('Y-m-d H:i:s');
$this->db->set('user_nicename', $nameVar);
$this->db->set('user_login', $emailVar);
$this->db->set('user_pass', $passwordVar);
$this->db->set('user_registered', $now);
$this->db->insert('doc_users');
this works for me in Codeigniter 3.0.6
$this->db->set('user_registered', 'NOW()', FALSE);
try this
first load date helper
To follow ci structure you have to use mdate() function otherwise you can also use date function
$this->db->set('user_nicename', $nameVar);
$this->db->set('user_login', $emailVar);
$this->db->set('user_pass', $passwordVar);
$this->db->set('user_registered', mdate("%Y-%m-%d %H:%i:%s"));
$this->db->insert('doc_users');
I would recommend using load the date helper.
mdate('%Y-%m-%d %H:%i:%s', now());
There is no need to use multiple sets you could simply put it in a array.
$data = array(
'user_nicename' => $nameVar,
'user_login' => $emailVar,
'user_pass' => $passwordVar,
'user_registered' => mdate('%Y-%m-%d %H:%i:%s', now())
);
$this->db->set($data);
$this->db->insert('doc_users');
Also make sure your user_registered database type is DATETIME
To set your current date_time_zone
Go to the config.php and add the code below
Example: date_default_timezone_set('Pacific/Auckland');
For your time zone you can find list here http://php.net/manual/en/timezones.php
$data = [
'type'=>$this->input->post('txttype')
//for getting input value of form
];
$this->db->set('column_name', 'NOW()', FALSE);
$this->db->insert('table_name', $data);
Also you can make a DB query to get current DB date/time:
$this->db->select('NOW() as db_date')->get()->row()->db_date
In Codeigniter, you have to load date helper as
$this->load->helper('date');. than after you have to define city for
timezone as date_default_timezone_set('Asia/Kolkata');.than after
you can set your time zone according your requirnment.
$this->load->helper('date'); // load Helper for Date
date_default_timezone_set("UTC");
echo $date=gmdate("F j, Y").'<br>'; // ie. May 23, 2018
if (function_exists('date_default_timezone_set'))
{
date_default_timezone_set('Asia/Kolkata'); // Specify your time zone according to your city
}
date_default_timezone_set('Asia/Kolkata'); // Defined City For Timezone
$currentDate =time();
$datestring = '%Y-%m-%d - %h:%i %a';
$time = time();
$better_date= mdate($datestring, $time).'<br>'; // i.e : 2018-05-23 - 09:52 am | For AM | PM result
$c_date=date("Y-m-d H:i:s").'<br>'; // 2018-05-23 09:52:36 | For Seconds Result
// Insert Date and Time to the Database
$data=array(
'name' =>'Rudra',
'email' =>'test#me.com',
'city' =>'Kolakata',
'data_time_on'=>$c_date
);
$this->db->insert('tableName',$data);
thanks for reading.
Just need to know how i convert datetime gotten from my sql tables in gmtime to datetime in user timezone.
the following is my code but doesn't seem to work..
//WHERE $post_arr[5] is date from sql
$user_date=convert_date_for_user($post_arr[5]);
function convert_date_for_user($date_time){
$user = JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone');
echo $tz_offset;
$user_date = JFactory::getDate($date_time,$timezone);
$user_date_str = $user_date->toUnix(true);
return $user_date_str;
}
It converts but I'm getting all the wrong time from the above code.
The simplest way to do it:
$useUserTimeZone = true;
JHtml::date($sqlGmtTimestamp , 'D F n, Y', $useUserTimeZone);
$sqlGmtTimestamp takes GMT timestamp/datetime
$useUserTimeZone is a flag to use user's timezone, otherwise server's timezone will be used.
more details here: http://docs.joomla.org/API16:JHtml/date
You don't specify your Joomla version but, did you try Joomla's JDate class directly?
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance('now', $timeZone);
// Gets the date as UNIX time stamp.
$myDate->toUnix():
// For your example using a method
function convert_date_for_user($date_time)
{
// Get the User and their timezone
$user = JFactory::getUser();
$timeZone = $user->getParam('timezone', 'UTC');
// Create JDate object set to now in the users timezone.
$myDate = JDate::getInstance($date_time, $timeZone);
return $myDate->toUnix();
}
This is the function that works for me:-
//WHERE date_time is the format of the date taken directly from database(ie: 0000-00-00 00:00:00)
function convert_time_zone($date_time){
$user =& JFactory::getUser();
$db = JFactory::getDBO();
$timezone=$user->getParam('timezone','UTC');
$time_object = new DateTime($date_time, new DateTimeZone('UTC'));
$time_object->setTimezone(new DateTimeZone($timezone));
$user_datetime=$time_object->format('Y-m-d H:i:s');
//SELECT ONLY 1 line below
return $user_datetime; //WOULD RETURN DATETIME IN 0000-00-00 00:00:00
//OR
return $time_object->getTimestamp(); //WOULD RETURN DATETIME IN UNIX TIMESTAMP
}
Its a little out of the way as i was hoping to use functions included in the joomla API to do it. If anyone could provide a better solution please do. and i select it as the right answer.
With Joomla 2.5+ (i think), you can use the following code
echo JHtml::_('date', $input, $format, $tz, $gregorian);
$input can be one of the following values:
"now" for the current time (DEFAULT)
A date/time string in a format accepted by date()
$format can be one of the following values:
NULL to use the default locale based format (DEFAULT)
A date format specification string (see http://php.net/manual/en/function.date.php)
$tz can be one of the following values:
TRUE to use the user's time zone (DEFAULT). Note: If the user's time zone is not set then the global config time zone is used.
FALSE to use global config time zone
NULL for no conversion
A timezone string (eg: "America/Los_Angeles", see http://php.net/manual/en/timezones.php)
$gregorian can be one of the following values:
TRUE to use Gregorian calendar
FALSE to NOT use Gregorian calendar (DEFAULT)
Having tried all the given possible solutions here and not getting the date in the user's timezone (Joomla! v.3.9.14), here's my (proven) solution:
$oUser_TZ = JFactory::getUser()->getTimezone();
$aUser_tz = (array)$oUser_TZ; // almost sure this step is not that necessary
$full_date = JFactory::getDate('now', $aUser_tz['timezone']); // pretty sure $oUser_tz->timezone will work
// I had try to use $full_date->Format('Y-m-d H:i:s') but it was giving me the non-converted-to-wanted-timezone date, so
$date_converted = substr($full_date, 0, 19);
date_converted gives me the date in format Y-m-d H:i:s and in the wanted timezone.
Try This:
$date = JFactory::getDate(); // now - 2014-03-11 08:45:22
$date->setOffset(8); // UTC+8
echo $date->toMySQL(); // wrong - 2014-03-11 08:45:22
echo '<br />';
echo $date->toFormat(); // right - 2014-03-11 16:45:22
JHtml::date($post_arr[5]);
If you want a different format, use the second parameter:
JHtml::date($post_arr[5], DateTime::RFC2822);
Which is equivalent to:
1. Create a JDate object with an UTC date read from the database
2. Get the correct Time Zone in Jomla Global Configuration and User Configuration
3. Call setTimeZone() to convert your JDate object to user local time
4. Call format() to format the JDate object as a well formatted string