How to find the difference in days between two dates in laravel? - php

I have stored the date as a string in my DB in this format (dd-mm-yyyy).
Here I want to check the difference in days between the current date and the date in DB.
Here is my controller code:
public function index()
{
$domain_count = domain_details::get()->count();
//var_dump($domain_data);
$domain_alert = domain_details::
where('domain_ex_date','>',date('j-m-y'))
->get();
return view('home1')->with('domain_count' , $domain_count)
->with('domain_alert' , $domain_alert);
How do I achieve this? Is my approach right?
The above code shows 2016 is greater than 2017. I can see my logic is wrong but how do I change this?

It's better to have your dates in a DATE column in a proper format, otherwise MySQL won't know how to calculate it. Since you don't, you'll have to convert it with str_to_date, passing in the raw command:
where(DB::raw("str_to_date('domain_ex_date','%d-%m-%Y')"),'>',date('Y-m-d'))

Related

Laravel automatically adding time to date

I seem to have a problem with my Laravel application, and I can't for the life of me figure out whats going on.
I have a simple date field in my MySQL database, its data type is just date, and for this example the value is 2020-08-13, but for some reason, when I try to access the date, it adds a timestamp on the end, minuses 1 day and throws a Carbon trailing data error.
It is definitely this date, because when I soft delete it, the error disappears.
As an example, the error for this date is
Carbon\\Carbon::rawCreateFromFormat('Y-m-d', '2020-08-12T23:0...', NULL)
So as you can see, it's removing a day and trying to format at 11pm the night before?
I have had similar issues to this before where Laravel was adding 0000-00-00 to the date, so I had to remove it in my accessor, but now that its throwing 11pm, my string replace doesn't work anymore. I can obviously just change the string replacer to look for 11pm, but I don't want to have to fix this every time the format changes.
My accessor code is as follows
public function getDateAttribute($value){
//String replace and remove the time from the value if it exists
$value = str_replace(' 00:00:00', '', $value);
return Carbon::CreateFromFormat('Y-m-d', $value)->format('d/m/Y');
}
Has anyone had an error like this before, or have any idea whats going on?
Before Laravel 7, dates would be serialized to a format like the following :
2019-12-02 20:01:00
But, Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models, with ISO-8601 date format. This ISO-8601 dates are always expressed in UTC, like this :
2019-12-02T20:01:00.283041Z
If you would like to keep using the previous behavior you can override the serializeDate() method on your model, add this into your model :
use DateTimeInterface;
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
first define you column to $dates property on your model :
$dates=['date']
then specify your date format by accessor :
public function getDateAttribute($value){
return $val->format('d/m/Y');
}
public function getDateAttribute($value){
// return 2020-08-17
$date = date('Y-m-d',strtotime($value));
return $date;
}
Make sure of the config file. You will find there a function of local time that can change its value from UTC to the local time of your country
config / app.php
'timezone' => 'Asia/Riyadh',
it's removing a day and trying to format at 11pm the night before
That's clearly a timezone shift (you're likely in GMT+1) and this is a shift to GMT+0 (UTC).
You should not trim the time to force "00:00:00" because this will only work in 1 timezone (there is no worldwide-midnight-moment, there is a different midnight moment in each timezone for each day), while your app now or later may handle multiple timezones. You should rather save the timezone ("Europe/London" for instance) in an other DB column and so you'll keep the complete information and when retrieving your date, you can calculate on the fly the midnight from (before) this date-time according to the user timezone.

php compare two date not work

I'm in a problem that i need an help because after research i have not found a solution.. I have to compare two date in PHP, the date of now with the date from Database.
Writing this:
strtotime(Date("d/m/Y H:i"))
Correct return the current timestamp.
But writing this:
strtotime($m['start_date'])
Work but response with a timestamp less than the current timestamp but the $m['start_date'] is from Database and it's like this: "2017-08-23 11:00:00"... It's not possible that the timestamp of 2017-08-23 11:00:00 it's less than the current timestamp!
And the weird part is that if i write this:
Date("d/m/Y H:i",strtotime($m['start_date']))
It response with the correct Date formatted with the string i passed to: 23/08/2017 11:00. How it possible? I have to compare the two timestamp but the output is that today come after tomorrow...
I have tested a lot of solution but not working at all. I have tried also to write this:
strtotime(Date("d/m/Y H:i",strtotime($m['start_date'])))
But not return nothing, 0.
I have also tried to put the second, but the result is the same.
I'm falling all for a stupid comparison from two date, help me!
After today i definitely hate work with Date
If you are trying to compare two timestamps from why don't just use the time() function and compare if it's less, greater or equal to the timestamp of the value received from the database by using strtotime($m['start_date']) for example
$db_time = strtotime($m['start_date']);
if ( time() > $db_time ) {
/**
** YOUR CODE
**/
}

PHP / SQL display dates in format

In an SQL database I'm storing various dates, such as date of birth and date they joined my system, in the standard SQL format YYYY-mm-dd, however I wish to display these to my British users (all my users) in the format dd-mm-YYYY.
I've tried pretty much everything I found online about doing this, however cannot decipher how it's done correctly. The code I list below is what I am currently using, however it does not display the correct date stored in the database and instead uses a completely random date of 01-01-1970. Some assistance on resolving this issue would be greatly appreciated.
while($row = $results->fetch_assoc()){
array_push($_SESSION["ActQueue"], array($row["username"], $row["surname"], $row["forename"], date('d-m-Y', $row["dob"]), $row["gender"], $row["joined"]));
}
$data = 0;
echo json_encode(['Username'=>$_SESSION["ActQueue"][0][0], 'Surname'=>$_SESSION["ActQueue"][0][1],'Forename'=>$_SESSION["ActQueue"][0][2],'DoB'=>$_SESSION["ActQueue"][0][3], 'Gender'=>$_SESSION["ActQueue"][0][4], 'Joined'=>$_SESSION["ActQueue"][0][5]]);
You need to convert your plain text date to time before passing to date() function
date('d-m-Y', strtotime($row["dob"]))
The date you receive 01-01-1970 its not a random date but its actually the first date from unix system
You need to use :
date('d-m-Y', strtotime($row["dob"]))
strtotime
You can use this this code to format your date
(new \DateTime($row["dob"]))->format('d-m-Y');

How to compare only date and year in php codeigniter

My model:
public function get_payscale() {
$this->db->from('payscale P')->join('employee E','E.employee_id = P.employee_id ');
$this->db->where('P.payscale_date',date('Y-m'));
return $this->db->get()->result_array();
}
I want to compare only the month and year with the db, in which the format is y-m-d, where I want only to retrieve the y-m using the where clause.
Use like this :
$this->db->where('EXTRACT(YEAR_MONTH FROM P.payscale_date)',date('Ym'));
This query will extract the Year and month from the date given column like 201605 (2016-05-21)
Not sure with exact syntax but something like below will work for you.
$this->db->where('year(Start_Date),year(curdate())');
$this->db->where('month(Start_Date),month(curdate())');
I have used the same condition in core PHP you can simply implement it on Codeigniter if any issue gets while implementing let me know
SELECT * FROM `test` WHERE Year('payscale_date') = 2016 and Month('payscale_date') = 05
If you have datetime type in your mysql table, and if you want to grab only the year from it, use this:
$this->db->->where('year(prdt.date_updated)',$year);
Its worked for me.
$this->db->where('month(uspl_date)=month(curdate())');

Timestamp Difference and Output

In My SQL Database I have a Timestamp Column with values like this one representing the Date of the last edit:
2015-01-17 08:55:34.000000
I want to compare the Date with the current date and when is the same day I want to echo Today and otherwise I want to Display the Date of the last edit:
$timefromdb = '2015-01-17 08:55:34.000000'
$edit = strtotime($timefromdb);
if($edit > $_SERVER['REQUEST_TIME']){echo "Today";}
else{
echo strftime("on %A, the %d %B %Y", $edit);
}
echo " at ".date('h:i',$edit)
It always Displays 01/01/1970. There must be a Problem with strtotime. I did a bit of research and it seems like my Timestamp Format isn't a valid one: http://php.net/manual/en/datetime.formats.php
Around the web are a lot of Questions about converting Timestamps but I just can't find the right one: I also got a bit confused by all the functions to convert date stuff.
So can someone Tell me how to get a valid Timestamp for using it in strftime and to compare it to the REQUEST_TIME.
Thanks in Advance!
UPDATE: As Always: The Problem sits in Front of the PC. I declared the Variable but never assgined the Timestamp to it :)
Chop off the .000000 from the date as it makes the date a format strtotime() cannot work with. There's several ways to do this. A simple substr is one of them.
$timefromdb = substr('2015-01-17 08:55:34.000000', 0, -7);
I'm not exactly understood you, but
try
1. compare gettype( $edit ) and gettype($_SERVER['REQUEST_TIME'])
2. not sure what $timefromdb will be more then $_SERVER['REQUEST_TIME'], because IMHO when user edited data, time of it action will me less then current time.

Categories