I need to set end_at attribute 30 days from current date. how can i do that in laravel 4.
When I have used bellow code I am getting error saying "Class 'Date' not found"
Please help me to fix this.
$sub->end_at = new Date('+30 days');
There is no Date class in PHP, there is only a DateTime class which you could use.
But since you're using Laravel, which uses the Carbon library by default, you can use that to handle dates because it has a better API. In your case you can do this:
use Carbon\Carbon;
...
$sub->end_at = Carbon::now()->addDays(30)->toIso8601String();
If you're trying to update a Eloquent model, then you can take advantage of Eloquent's integrated date/time column handling. In your model you can add the dates property with this value:
protected $dates = ['end_at'];
and now when assigning a timestamp to the end_at column, Laravel will automatically transform and save it to the correct format in your database. So you'll only need to use this:
$sub->end_at = Carbon::now()->addDays(30);
This will return that in the format appropriate for MySQL
$sub->end_at = date('Y-m-d H:i:s', strtotime('+30 days'));
Related
I'm struggling with Laravel date formats, using it with PgSQL.
My need :
input date must be in this ISO8601 format: Y-m-d\TH:i:s\Z (example: 2016-05-13T10:05:00Z)
output must be in the same format
PgSQL stores it in the format Y-m-d H:i:s (example: 2016-05-13 10:05:00)
The hard part is to configure Laravel to globally accept a particular date format in input and output, but without changing "internal" format.
A property can be overridden to customize format, but it acts globally:
protected $dateFormat = 'Y-m-d\TH:i:s\Z';
This leads to errors when retrieving dates from database (trying to convert a PgSQL date with a custom mask: InvalidArgumentException).
I would like to avoid using a Middleware or do it manually in each controller response, is there any way?
Sounds like you want to use accessors and mutators. Here's a basic example with a class that has a my_date column, the conversion might not be exactly right (I'm just assuming strtotime() will work) but that should be easy for you to fix.
class SomeModel extends Model
{
// triggered whenever you retrieve the date from the db
public function getMyDateAttribute($value)
{
return date('Y-m-d\TH:i:s\Z', strtotime($value));
}
// triggered whenever you insert the date into the db
public function setMyDateAttribute($value)
{
$this->attributes['my_date'] = date('Y-m-d H:i:s', strtotime($value));
}
}
Now, your database can use one datetime format and the other parts of your application can use another. If you want it to be reusable for other models, you can extract it to a trait as long as the columns are named the same.
Hi Im using firefox and CoffeeScript in an app, I want to get current date with momentjs using default method moment() however when I debug the code I seeinvalid Date, it is very weird, this is my code:
questionStarts =
started_at: moment()
running: true
Then later in my code I create another object and add the property
answer = {}
answer.started_at = questionStarts.started_at
But when I check answer.started_at I get back Invalid date any idea?
Moment has an alternate constructor for strange dates. Since I can't see the value of answer.started_at in your code, I can only guess about how to solve your problem.
Consider for example some strange date format like 08.16.2015 00:00:00. Trying to construct a moment object from it will give the same error you have, Invalid date. That's what happens if you tried constructing my example like this:
//this doesn't work, throws Invalid date message
var ex = moment('08.16.2015 00:00:00');
So, to fix my problem, I give another constructor that informs Moment of the strange date format.
//this does work, however
var ex = moment('08.16.2015 00:00:00', 'MM.DD.YYYY hh:mm:ss');
Now, I can use ex as a typical moment object taking advantage of moment's other methods such as format() diff() and isBetween().
I'm working on an app that allows the user to edit several dates in a form. The dates are rendered in the European format (DD-MM-YYYY) while the databases uses the default YYYY-MM-DD format.
There are several ways to encode/decode this data back and forth from the database to the user, but they all require a lot of code:
Use a helper function to convert the date before saving and after retrieving (very cumbersome, requires much code)
Create a separate attribute for each date attribute, and use the setNameAttribute and getNameAttribute methods to decode/encode (also cumbersome and ugly, requires extra translations/rules for each attribute)
Use JavaScript to convert the dates when loading and submitting the form (not very reliable)
So what's the most efficient way to store, retrieve and validate dates and times from the user?
At some point, you have to convert the date from the view format to the database format. As you mentioned, there are a number of places to do this, basically choosing between the back-end or the front-end.
I do the conversion at the client side (front-end) using javascript (you can use http://momentjs.com to help with this). The reason is that you may need different formats depending on the locale the client is using (set in the browser or in his profile preferences for example). Doing the format conversion in the front-end allows you to convert to these different date formats easily.
Another advantage is that you can then use the protected $dates property in your model to have Laravel handle (get and set) these dates automatically as a Carbon object, without the need for you to do this (see https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L126).
As for validation, you need can then use Laravel's built-in validation rules for dates, like this:
'date' => 'required|date|date_format:Y-n-j'
While client-side is good for UX, it doesn't let you be sure, all will be good.
At some point you will need server-side validation/convertion anyway.
But here's the thing, it's as easy as this:
// after making sure it's valid date in your format
// $dateInput = '21-02-2014'
$dateLocale = DateTime::createFromFormat('d-m-Y', $dateInput);
// or providing users timezone
$dateLocale =
DateTime::createFromFormat('d-m-Y', $dateInput, new DateTime('Europe/London'));
$dateToSave = $dateLocale
// ->setTimeZone(new TimeZone('UTC')) if necessary
->format('Y-m-d');
et voila!
Obviously, you can use brilliant Carbon to make it even easier:
$dateToSave = Carbon::createFromFormat('d-m-Y', $dateInput, 'Europe/London')
->tz('UTC')
->toDateString(); // '2014-02-21'
Validation
You say that Carbon throws exception if provided with wrong input. Of course, but here's what you need to validate the date:
'regex:/\d{1,2}-\d{1,2}-\d{4}/|date_format:d-m-Y'
// accepts 1-2-2014, 01-02-2014
// doesn't accept 01-02-14
This regex part is necessary, if you wish to make sure year part is 4digit, since PHP would consider date 01-02-14 valid, despite using Y format character (making year = 0014).
The best way I found is overriding the fromDateTime from Eloquent.
class ExtendedEloquent extends Eloquent {
public function fromDateTime($value)
{
// If the value is in simple day, month, year format, we will format it using that setup.
// To keep using Eloquent's original fromDateTime method, we'll convert the date to timestamp,
// because Eloquent already handle timestamp.
if (preg_match('/^(\d{2})\/(\d{2})\/(\d{4})$/', $value)) {
$value = Carbon\Carbon::createFromFormat('d/m/Y', $value)
->startOfDay()
->getTimestamp();
}
return parent::fromDateTime($value);
}
}
I'm new in PHP, so I don't know if it's the best approach.
Hope it helps.
Edit:
Of course, remember to set all your dates properties in dates inside your model. eg:
protected $dates = array('IssueDate', 'SomeDate');
Hi I need to check multiple dates for reminder section of my application.
But when I fetch dates from mongodb I am getting this:
DateTime Object
(
[date] => 2014-03-31 15:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)
I am trying this to access date parameter but it is showing me error that dateTime object can not converted into string.
I am looping dateandtime.
Please let me know how can I access date in this situation in symfony.
Thanks
The assumption of others is that you recieve a MongoDate object back but you don't since I beleive Symfony actually converts it to a DateTime: http://www.php.net/manual/en/class.datetime.php (I think this comes from Doctrine 2)
What you can do is use the format function: http://www.php.net/manual/en/datetime.format.php like so:
$date->format('Y-M-d h:i:s')
You can do this in php (symphony is a php-framework).
All you need is something like this:
date('Y-M-d h:i:s', $yourDateTimeObject->sec);
You can also use __toString method from MongoDate class, but I actually prefer the previous method with sec.
I have a form, that saves date of birth in the database. This form passes three variables to php: $ayear $amonth $adate
Now I need to save these in the database in a format: 00/00/0000 (or 00/00/00, if 00/00/0000 is not supported).
I need to create a date() variable, but I dont know how. All the examles on the internet use time() or now() which are not usefull in my case. Can someone give me the right function?
Thank you for your time!
If you're using MySQL you'll want to save as YYYY-MM-DD with the field type set to date. I'd save this variables value to the database.
$birthday = implode('-', array($year, $month, $day));