it is not able to store day,month,year in the format of dd/mm/yy in data base by getting value through the form of Yii.it is only possible to store in the format of year/month/date can any body answer.
Your question is not clear. I am guessing when you save date submitting the form it saves in mysql default format and then when you display it, it is not displayed in your desired format. If this is the case, I would recommend the best way to solve this is to change the date format in the model. You can use the 'before save' and 'after find' methods in the model to change the date format before saving to db and also change it when it is pulled from db. The actual date format will remain the same in db, but it will also display in the format you want it to. Here's an example,
protected function beforeSave()
{
if($this->date!=null){
$this->date=date('Y-m-d', strtotime($this->date));
}
return TRUE;
}
public function afterFind()
{
if($this->date!=null){
$this->date = date('d F Y',strtotime($this->date));
}
return true;
}
Related
I'm trying to use 'type'=> 'datetime-local' in my form to create the date time picker.
In the view everything works fine but cakephp can't handle the format of the result.
I've tried to cast it to a Cake\I18n\Time but it ignores the set time and is using the current time.
Did anyone use the html5 date time picker in cakephp?
Is there any intention to make it the default picker in cake?
The cakephp default picking option with a lot of select boxes is not really handy.
CakePHP doesn't support the format used by the HTML5 datetime-local input (YYYY-MM-DDTHH:MM) out of the box (yet).
You can solve this by for example using a custom/extended database type that adds a proper format to the existing default formats (this will affect all datetime fields/columns), like:
// in src/Database/Type/DateTimeType.php
namespace App\Database\Type;
class DateTimeType extends \Cake\Database\Type\DateTimeType
{
public function __construct($name = null)
{
$this->_format[] = 'Y-m-d\TH:i'; // date() compatible format
parent::__construct($name);
}
}
// in config/boostrap.php before `Type::build('datetime')` is invoked
Type::map('datetime', \App\Database\Type\DateTimeType::class);
by parsing the input manually before marshalling:
// in a table class, a behavior, or a listener for the Model.beforeMarshal event
public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)
{
if (isset($data['fieldName']) &&
is_string($data['fieldName'])
) {
$data['fieldName'] = \Cake\I18n\Time::parseDateTime(
$data['fieldName'],
"yyyy-MM-dd'T'HH:mm" // ICU compatible format
);
}
}
or by enabling localized parsing, and supplying a matching format (this will restrict all datetime fields/columns to this one format):
// in config/bootstrap.php
Type::build('datetime')
->useImmutable()
->useLocaleParser()
->setLocaleFormat("yyyy-MM-dd'T'HH:mm"); // ICU compatible format
See also
Cookbook > Database Access & ORM > Database Basics > Adding Custom Types
Cookbook > Database Access & ORM > Saving Data > Modifying Request Data Before Building Entities
Cookbook > Internationalization & Localization > Parsing Localized Datetime Data
Cookbook > Date & Time > Formatting > Cake\I18n\Time::i18nFormat()
I have not yet understood where concretely is the problem is...
I have a Doctrine entity with date field:
/**
* #var \DateTime
*
* #ORM\Column(name="day", type="date")
*/
private $day;
Also I have an entity form with date type field:
$builder->add('day', DateType::class, ['widget' => 'single_text'])
And when I try to save the form with value "2016-02-14" I see that it becomes "2016-02-13" (a day earlier) in MySQL and in PHP after saving. When I began looking for logs, I saw that the query parameter value is "2016-02-13 23:00:00".
But I don't understand why it happens this way.
I have the same time and timezone in system (Ubuntu), PHP and MySQL (Europe/Moscow timezone).
I use date type, not datetime, so there should not be time at all.
When I tried to debug it, I saw that code
#vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateType.php
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value !== null)
? $value->format($platform->getDateFormatString()) : null;
}
works correctly. It makes correct format "Y-m-d", but in the symfony log value is with time.
I need an advice about how to find, where my date transforms.
I had a similar problem and used a quick-and-dirty hack. On the setter used for the $day property, just set the time to be midday.
public function setDay(\DateTime $day)
{
$this->day = $day;
$this->day->setTime(12, 0, 0);
return $this;
}
I have a column in mysql database named time_start which type is TIME.
I am trying to format the displayed time in my view from H:i:s to simple H:i, so instead of 20:00:00 i will get 20:00.
Firstly i thought i can use format() method, but it's supposed to be used with timestamps, so of course i get error Call to a member function format() on a non-object.
I'm sure it's a simple question, but i can't solve this.
-EDIT-
Forgt to mention. I am working with a many to many relationship and i'm calling my data like:
$schedule->time_start
Here i would like to show the time in H:i format, not H:i:s.
Have you tried an accessor method? I.e. in the Schedule model,
/**
* Return a truncated version of the timestamp.
* #param $value original value of attribute
* #return string truncated value
*/
public function getTimeStartAttribute($value)
{
// Input is HH:MM:SS
return substr($value, 0, 5);
// Output is HH:MM
}
Then $schedule->time_start ought to return the time in HH:MM format.
i have an object student. then there is a property called expiry date. this is need to be set with the database sysdate + a value(1000).
so how can i save with jpa. can't i do it on the jpa prepared statement query itself?
if i use sql.date is it exactly give the same value as when we are saving as 'sysdate'?
can't i do it with on the query itself?
other properties can be set to the object. but the problem is this expiry date as it needs the sysdate and add another value to it eg: expiry date = sysdate + 1000; how can i do it with jpa prepared statements. please reply me
What about use a seperate query to retrieve sysdate and set it to your object.
I usally create a Clock to handle this:
public interface Clock {
Date now();
}
public class HibernateClock implements Clock {
//use query to retieve the db sysdate
}
You can add it in java itself. Use calendar object to add days.
Calendar expirydate=Calendar.getInstance();
expirydate.add(Calendar.DATE, 1000);
then
expirydate.getTime() will give you expire date object.
Why do you want to use sysdate? Its syntax is database specific and also dependent on the DB-hosting machine's clock, rather than on your application-hosting machine's clock.
Easiest way is to use java.util.Date as the expiryDate's type and the value of new Date(System.currentTimeInMillis() + 1000). Use this value in the field's declaration for featuring it as default value on new Student creation or use it as the value passed to the setter when modifying an existant Student.
public class Student {
...
/**
* Using java.util.Date here. Hibernate knows to convert it automagically to java.sql.Date.
* Set default value to current time + 1 second, if this is your requirement.
*/
private Date expiryDate = new Date(System.currentTimeInMillis() + 1000);
public void setExpiryDate(final Date expiryDate) {
this.expiryDate = expiryDate;
}
...
}
I have a domain class that needs to have a date after the day it is created in one of its fields.
class myClass {
Date startDate
String iAmGonnaChangeThisInSeveralDays
static constraints = {
iAmGonnaChangeThisInSeveralDays(nullable:true)
startDate(validator:{
def now = new Date()
def roundedDay = DateUtils.round(now, Calendar.DATE)
def checkAgainst
if(roundedDay>now){
Calendar cal = Calendar.getInstance();
cal.setTime(roundedDay);
cal.add(Calendar.DAY_OF_YEAR, -1); // <--
checkAgainst = cal.getTime();
}
else checkAgainst = roundedDay
return (it >= checkAgainst)
})
}
}
So several days later when I change only the string and call save the save fails because the validator is rechecking the date and it is now in the past. Can I set the validator to fire only on create, or is there some way I can change it to detect if we are creating or editing/updating?
#Rob H
I am not entirely sure how to use your answer. I have the following code causing this error:
myInstance.iAmGonnaChangeThisInSeveralDays = "nachos"
myInstance.save()
if(myInstance.hasErrors()){
println "This keeps happening because of the stupid date problem"
}
You can check if the id is set as an indicator of whether it's a new non-persistent instance or an existing persistent instance:
startDate(validator:{ date, obj ->
if (obj.id) {
// don't check existing instances
return
}
def now = new Date()
...
}
One option might be to specify which properties you want to be validated. From the documentation:
The validate method accepts an
optional List argument which may
contain the names of the properties
that should be validated. When a List
is passed to the validate method, only
the properties defined in the List
will be validated.
Example:
// when saving for the first time:
myInstance.startDate = new Date()
if(myInstance.validate() && myInstance.save()) { ... }
// when updating later
myInstance.iAmGonnaChangeThisInSeveralDays = 'New Value'
myInstance.validate(['iAmGonnaChangeThisInSeveralDays'])
if(myInstance.hasErrors() || !myInstance.save(validate: false)) {
// handle errors
} else {
// handle success
}
This feels a bit hacky, since you're bypassing some built-in Grails goodness. You'll want to be cautious that you aren't bypassing any necessary validation on the domain that would normally happen if you were to just call save(). I'd be interested in seeing others' solutions if there are more elegant ones.
Note: I really don't recommend using save(validate: false) if you can avoid it. It's bound to cause some unforeseen negative consequence down the road unless you're very careful about how you use it. If you can find an alternative, by all means use it instead.