I use a timepicker to get a time string(eg: '1:00am' or '12:00pm'). I need to modify and store this in a mysql TIME data type column as eg: '12:00:00'. Now, since the TIME column stores in 24 hrs format, I need to "modify" it. I can't seem to find any help to modify using Carbon, since I'm not using any dates. I'm using a mutator in Laravel, but would like to know if there is a better way like using Carbon for dates.
public function setTimeAttribute($time) {
if(substr($time, -2, 0) == 'am') {
// do nothing
} else if(substr($time, -2, 0) == 'pm') {
// increase hours.ie: 1:00pm to 13:00:00
}
}
Any help would be appreciated! Thanks.
Use PHP strtotime() function.
$time = "12:00am";
$timestamp = strtotime($time);
echo $timestamp;
//Will print something like: 1469228400
Or any other date format you prefer.
It's best to store time as timestamp, to convert it back you can use date() function.
E.g: $value = date("H:i:s", $timestamp);
Related
I work on one project with PHP and Mysql and I need to calculate the ages but I need delete the hours, minutes and seconds part. Here is an example:
The date of birth 2018-03-06 17:35:00 but
I need 2018-03-06 00:00:00
Here is my code:
function FetchAgeCaduce($MaxDias=3){
$fechaInicial = time();//date("Y-m-d");
$fecha = date("d/m/Y",$FechaFinal);
$fechaInicial = strtotime("d/m/Y",$fecha);
for ($i=0; $i<$MaxDias; $i++)
{
$Segundos = $Segundos + 86400;
$caduca = time()+$Segundos;//date("D",time()+$Segundos);
$var = date("D",$caduca);
if ($var == "Sat")
{
$i--;
}
else if ($var == "Sun")
{
$i--;
}
else
{
$FechaFinal = time()+$Segundos;
}
}
return $FechaFinal;
}
How can I work on it to get the expected result?
The right way / The MySQL way:
Store your data as DATE in MySQL, not DATETIME. DATE itself is described here. It does not store time, so you'll always have 00:00:00 as default.
The less right way / The PHP way:
Jay, Zeus, Freaking, K. Reist. Learn to use DateTime already, stop using date! It's like every second question here and noone learns DateTime!
Use it!
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
The output:
2018-03-06 00:00:00
P.S. $FechaFinal on line 5 is not defined.
You can format the date on either the application or database layer.
Using MySQL
You can use MySQL DATE_FORMAT Function
to parse the date into the wanted format.
SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') dob;
See DEMO on SQL Fiddle.
Using PHP
Say you don't want to format the date in the database layer, may be because you would need to use the time part in some other calculations. Use the date functions as illustrated below:
$dt = new DateTime();
echo $dt->format("Y-m-d 00:00:00");
//getting the expected date from the formatted string
$formateDate = DateTime::createFromFormat('Y-m-d H:i:s', $dt->format("Y-m-d 00:00:00"));
this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}
I have a field (nonTimeStampDate) that has date like this
2010-03-15
and I want to check it against another field (timeStampDate) which is
2010-03-15 15:07:45
to see if the date matchs. But as you can see since the format is different it doesnt match even though the date is same.
Any help will be appreciated.
thanks
My first thought is using date() and strtotime() to reformat them.
$date1 ="2010-03-15";
$date2 = "2010-03-15 15:07:45";
if (date('Y-m-d', strtotime($date1)) == date('Y-m-d', strtotime($date2)))
{
//do something
}
This would work and give you more flexibility in how the two dates formatted to begin with. Not the most elegant.
You might want to try this code:
if (strpos($date1, $date2) !== false) {
// Your code here
}
It is a bit faster than exploding the value by a space as suggested by Anax. Make sure that $date2 contains the shorter of the two dates.
If you are certain about the input string format, you need to split it and take the first part, in order to compare it with your original date:
$splits = explode(' ', $original);
$datapart = $splits[0];
if ($datepart == $nonTimeStampDate) {
// your code here
}
What Anax says, or if these values are in MySQL tables, you can use MySQLs datetime functions (like DATE()) to compare them in MySQL.
Then, just compare the date part:
<?php
if( substr('2010-03-15 15:07:45', 0, 10) == '2010-03-15' ){
echo 'Dates match';
}
?>
Whatever, if you need to do serious date handling, you need to use a proper format, such as a DateTime object.
$firstDate = date("Y-m-d", strtotime("2010-03-15"));
$secondDate = date("Y-m-d", strtotime("2010-03-15 15:07:45"));
if( $firstDate == $secondDate ) {
// true
}
I'm trying to do a function that will check the php date against what is in the database. If the current date (YYYY-MM-DD HH:MM:SS) is 24 hours after the stored database date, then it will continue, otherwise it won't do anything.. If that makes sense?
Here's how I'm trying to get it to work, but not 100% sure how:
$now = date("Y-m-d H:i:s");
foreach($results as $item) {
if ( /*item date is 24 hours or more earlier than $now*/ ) { /* this is what I'm not sure how to do */
//do something
} else {
//do nothing
};
};
If someone could help me get this working, I'd greatly appreciate it. I just don't know how to compare $item->date with $now and see if $item->date is 24 hours or more behind $now..
You can use strtotime instead of date math. Personally I think it reads much better.
if (strtotime($item->date) <= strtotime('-1 day')) {
// date is more than or equal to 24 hours old
}
foreach($results as $item) {
if (time() >= strtotime($item['date']) + 86400) {
// current time is 86400 (seconds in one day) or more greater than stored time
} else {
//do nothing
};
};
Note that if the stored date isn't in the same timezone as the server you'll need to mess with timezones - see here for starters.
Note that I store dates and times in MySQL as Unix timestamps to avoid some of these problems. I know it's not good database practice, but then PHP stores times as Unix timestamps anyway.