I have this to select a date from a mysql db, and compare it to an array of month-names in swedish language.
$monthnames = array("","Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December");
$postdate = $monthnames[date("n", strtotime( $row['modify_date'] ))];
//Outputs something like '12 Februari'
Here is the prob, I want to check the $postdate variable and change it to "Today", "Yesterday" and "Day before yesterday" according to the date, how can I do so?
Thanks
If you're using timestamps to store dates in the database:
You can have preset intervals like:
$day = mktime(0,0,0,2,1,2001)-mktime(0,0,0,1,1,2001);
And you can compare the time now - timestamps/dates you have in the database with those intervals.
For example, let's say $dbTime contains a timestamp fetched with mysql:
$time = time() - $dbTime;
if($time<$day)
echo 'posted today';
elseif($time<($day*2))
echo 'posted yesterday';
etc etc.
Then you can use PHP's Date function to echo hrs, minutes, secs, or dates, if they are larger than your predefined intervals.
There is no such in-built function in PHP. You got to do calculations, the mktime function can be your friend in this case.
if (date of $timenow == date of $timepost) { today; }
else if (date of $timenow - 24h == date of $timepost) { yesterday; }
etc.
Be aware about summer/winter time change, timezones etc. so try to use mktime()
http://php.net/date
Related
I have SQLite DB one table contains datetime field
with datatype "timestamp" REAL value is 18696.0
attach image for table structure
So, I want this 18696.0 value to be converted into MySQL Y-m-d format and result should be 2021-03-10
I have didn't found any solution online. any help would be appreciated.
SQLite timestamp converted into MySQL timestamp.
EDIT: Thankyou for updating your question with the correct number and what date it should represent.
You can achieve what you need with a function that adds the days onto the Unix Epoch date:
function realDateToYmd($real, $outputFormat='Y-m-d')
{
$date = new DateTime('1970-01-01');
$date->modify('+' . intval($real) . ' days');
return $date->format($outputFormat);
}
echo realDateToYmd('18696.0');
// returns 2021-03-10
SQLite dates stored in REAL data type stores dates as a Julian Day.
From https://www.sqlite.org/datatype3.html
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
PHP has a jdtogregorian function, in which one comment has a handy function to convert to ISO8601 dates:
function JDtoISO8601($JD) {
if ($JD <= 1721425) $JD += 365;
list($month, $day, $year) = explode('/', jdtogregorian($JD));
return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
echo JDtoISO8601('17889.0');
// Results in -4664-11-16
The results don't exactly look right, is it definitely 17889.0 in SQLite?
If this float number 18696.0 represents the number of days since 1970-01-01 then the date can also be calculated like this:
$days = 18696.0;
$dt = date_create('#'.((int)($days * 86400)));
$mysqlDate = $dt->format('Y-m-d'); //"2021-03-10"
background information
Or simply with gmdate:
$mySqlDate = gmdate('Y-m-d',$days*86400);
The days are simply converted into seconds to get a valid timestamp for gmdate.
Try this:
<?php
echo date('Y-m-d H:i:s', 17889);
?>
Output:
1970-01-01 04:58:09
It is necessary to calculate age based on date of birth. Information on date of birth is stored in the database in Unix Time.
I do not know PHP, has only just started to edit my existing code to get what I need.
Example:
$tpl->set( '{birthday}', langdate( "D M Y", $row['birthday'] ) );
Displays available in a CMS tag {birthday} for date of birth, takes Unix Time value from a database's row birthday and converts to a clear view "Date Month Year".
I want to create available in CMS tag {age} and through him publish age.
I suppose something like this:
$tpl->set( '{age}', current date - $row['birthday'] ) );
But how to do it - no idea ...
<?php
$now = strtotime(date('Y-m-d')); // Today in UNIX Timestamp
$birthday = strtotime(date('D M Y', strtotime($row['birthday']))); // Birthday in UNIX Timestamp
$age = $now - $birthday; // As the UNIX Timestamp is in seconds, get the seconds you lived
$age = $age / 60 / 60 / 24 / 365; // Convert seconds to years
echo floor($age); // Round down to whole integer and echo it
?>
This is in my opinion the easiest way to calculate with dates as its easy to calculate with seconds. Not much of using the brain is needed :)
But the more beautifull way is:
<?php
$birthday = new DateTime($row['birthday']);
$now = new DateTime();
$age = $now->diff($birthday);
echo $age -> y;
?>
you can do this in the query with
SELECT .. TIMESTAMPDIFF(YEAR, FROM_UNIXTIME(dob), NOW()) as AGE ..
This works for me
echo date("Y", time()) - date("Y", $birth_in_unix_format);
I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.
You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.
You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)
$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');
$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}
In my PHP application I'm trying to compare date time values like the following:
if($datetime_from_db < date('Y-m-d H:i:s'))
{
// then do something
}
Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.
Comparing a string like "2011-02-14 15:46:00" to another string doesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:
strtotime($datetime_from_db) < time()
If you want this to work with dates past 2038, you can't use strtotime() or time().
See this question for the explanation.
A better approach:
new DateTime($datetime_from_db) < new DateTime();
This may help you.
$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);
if (strtotime($expectedDate) > strtotime($today)) {
echo "Expected date is greater then current date";
return ;
} else
{
echo "Expected date is lesser then current date";
}
Here is a solution where we use strtotime. I give two examples.
First one comparing the whole timestamp. Second one is just compare the date.
<?php
$date = "2022-10-06 17:49:10"; // string. can set any current timestamp
#example 1 - compare the date and time Y-m-d H:i:s
if(date("Y-m-d H:i:s" , strtotime($date)) >= date("Y-m-d H:i:s")){
echo "the date checked is bigger than today";
}else{
echo "the date checked is smaller than today";
}
#example 2 - compare the date only Y-m-d
if(date("Y-m-d" , strtotime($date)) == date("Y-m-d")){
echo "same day is true";
}else{
echo "same day is false";
}
I have a general question on calculating dates with php.
What happens if I store a timestamp like this in my database:
$db_timestamp = '2010-01-31 00:00:00';
and then run a daily script that checks if a month has passed since the timestamp was saved in the database:
if ($db_timestamp == make_unix_timestamp(mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")), TRUE, 'eu')))
{
do something
};
my problem is that i just realized that this wouldn't work for all dates. in this case 'do something' would not be called in February, since February doesn't have a 31st day. any idea on how to implement something like that?
First, your DBMS should have a data type for date/time. They all store timestamps in a similar way.
MySQL then provides a function called UNIX_TIMESTAMP() if you need to return a timestamp PHP can understand.
SELECT UNIX_TIMESTAMP(`createTime`) FROM `articles`;
The opposite function is called FROM_UNIXTIME():
INSERT INTO `articles` (`createTime`) VALUES ( FROM_UNIXTIME(12345678) );
MySQL (or another DBMS for that matter, but I'm using MySQL as an example) has a slew of other functions to calculate time differences. For example, to know if an article is more than one month old, use can use DATE_SUB():
SELECT * FROM `articles`
WHERE `article`.`createTime` <= DATE_SUB(NOW(), INTERVAL 1 MONTH);
(In MySQL5 and above, you can also write it as such)
SELECT * FROM `articles`
WHERE `article`.`createTime` <= (NOW() - INTERVAL 1 MONTH);
$ts = strtotime($db_timestamp);
if ($ts < (time() - 2592000))
{
do something;
}
2592000 seconds = 30 days
You could use date_diff http://us3.php.net/manual/en/datetime.diff.php
or do a comparison of the timestamp in your database with
strtotime("-1 month");
You could check the timestamp using a query:
MySQL:
select date from table where date < now() - INTERVAL 1 MONTH;
It kind of depends on how you consider "one month".
If "one month" means "30 days", a solution would be to compare the timestamp you get from the database with the current timestamp :
$db_timestamp = strtotime('2010-01-31');
$current_timestamp = time();
var_dump( ($current_timestamp - $db_timestamp) / (24*3600) );
If the difference is 30 days... that's it.
A couple of notes :
strtotime converts a date to an UNIX timestamp-- i.e. the number of seconds since 1970-01-01
time returns the current UNIX timestamp
you can compare timestamps : they only represent a number of seconds ; and there are 24*60*60 seconds per day ;-)