I have
date("M.", $datetime)
I want to get this output:
Jan.
Feb.
Mar.
Apr.
May (no dot necessary)
Jun.
Jul.
…
I dont like the idea of an if-statement to check the length/number of month every time a date is generated.
Is there a approach that is more simple? Like changing the month-name in general? Or hooking into the date function itself to implement an if-statement that runs every time the date function runs.
Thanks
If you don't want the dot to appear after May month, you will need a check of some sort - which normally is an if. You could do something like this, check if the month returned by date() isn't May, and add a dot after if it isn't.
$date = date("M", $datetime);
if (date("M") != "May")
$date .= ".";
Otherwise you'd need to implement a function of your own, but in the end - you will have to end up with this again, there's really no way around it - and this is by far the simplest and cleanest way.
You could wrap this into a function. You can't alter the date() function directly, but you can create one of your own.
function my_date($format, int $timestamp = null) {
if ($timestamp === null)
$timestamp = time();
$date = date($format, $timestamp);
if ($format == "M" && date("M", $timestamp) != "May")
$date .= ".";
return $date;
}
Then use it as
echo my_date("M", $datetime);
This seems to be a bit of a hammer to crack a nut, or to avoid an IF statement in this case, but you can create an array with your month names in it and use that to output different month names if you like
$m_arr = [0,'Jan.','Feb.','Mar.','Apr.','May','Jun.',
'Jul.', 'Aug.', 'Sep.','Oct.','Nov.','Dec.'];
$m = (int)date('n', $datetime);
echo $m_arr[$m];
Related
I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!
function getBirthDayFromRd($rd){
$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);
if($month>=51 and $month<=62){
$month = $month - 50;
}
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:
function getBirthDayFromRd($rd){
$date = DateTime::createFromFormat('ymd',$rd);
if($date->format('Y') > date("Y")) {
$date->modify('-100 years');
}
return $date->format('d.m.Y');
}
DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.
update
Just fixed a bug where pre-1970 dates were shown 100 years in the future.
Demo
I solve it another way, but u started me up.
if($year < 70){
$year = $year+1900;
$time = date_create_from_format("d.m.Y", $day.".".$month.".".$year);
return date_format($time, "d.m.Y");
}else{
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
I'm a PHP beginner and been struggling unsuccessfully with the php documentation. Seems a lot of ways to do what I want.
Basically I need a php page to check an "ugly" date/time variable appended to a URL - it must convert it into a usable format and subtract it from the current date/time. If the result is less than 48hrs then the page should redirect to "Page A" otherwise it should redirect to "Page B"
This is what the URL and variable looks like.
http://mysite.com/special-offer.php?date=20130527212930
The $date variable is the YEAR,MONTH,DAY,HOUR,MINUTE,SECOND. I can't change the format of this variable.
I'm guessing PHP can't use that string as it is. So I need to split it somehow into a date format PHP can use. Then subtract that from the current server date/time.
Then put the result into an if/else depending on whether the result is more or less than 48hrs.
Am I right in theory? Can anyone help me with the "practise"?
Thanks!
Take a look at the DateTime class and specifically the createFromFormat method (php 5.3+):
$date = DateTime::createFromFormat('YmdHis', '20130527212930');
echo $date->format('Y-m-d');
You might need to adjust the format depending on the use of leading zeros.
PHP 5 >= 5.3.0
$uglydate = '20130527212930';
// change ugly date to date object
$date_object = DateTime::createFromFormat('YmdHis', $uglydate);
// add 48h
$date_object->modify('+48 hours');
// current date
$now = new DateTime();
// compare dates
if( $date_object < $now ) {
echo "It was more than 48h ago";
}
You can use a regular expression to read your string and construct a meaningful value.
for example
$uglydate = "20130527212930";
preg_match("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", $uglydate, $matches);
$datetime = $matches[1] . "-" . $matches[2] . "-" . $matches[3] . " " . $matches[4] . ":" . $matches[5] . ":" . $matches[6];
//then u can use $datetime in functions like strtotime etc
Whoa! you all have WAY too much time on your hands... Nice answers... oh well, i'll pop-in a complete solution...
<?php
$golive = true;
if (preg_match('|^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})|', $_GET['date'], $matches)) {
list($whole, $year, $month, $day, $hour, $minute, $second) = $matches;
// php: mktime function (using parameters derived
$timestamp = mktime($hour,$minute,$second,$month,$day,$year);
$diff = time()-$timestamp;
$diffInHours = $diff / 3600 ;
// if less, than 48
if ( $diffInHours < 48 ) {
$location = "http://bing.com";
} else {
$location = "http://google.com";
}
//
if ( $golive ) {
header("Location: ".$location);
exit();
} else {
echo "<p>You are would be sending the customer to:<br><strong>$location</strong>";
}
} else {
echo "<p>We're not sure how you got here, but... 'Welcome!'???</p>";
}
That oughta do it.
By the way, on another note, I'd heavily suggest you go back to the sending party of that URL and definitely reconsider how this is being done. As this is VERY easily tweakable (URL date= value), thus not really protecting anything, but merely putting the keys on the front porch next to the 'Guardian Alarms Installed at This House' {sign} :).
Assuming the input is in the correct format (correct number of characters and all of them digits) you'll need 1 substring of length 4 and the rest of lenght 2. For simplicity I'll ignore the first 2 chars (the 20 part from 2013) with substr
$input=substr($input, 2, strlen($input));
Now I can treat all the remaining elements in the string as 2-char pairs:
$mydate=array(); //I'll store everything in here
for($i=0; $i<=strlen($input)-2; $i+=2){
$mydate[$a]=substr($input, $i, $i+2);
$a++;
}
Now I have year, month, day etc. in an array indexed from 0 to 5. For the date difference I'll put the array into mktime:
$timestamp = mktime(mydate[3], mydate[4], mydate[5], mydate[1], mydate[2], mydate[0]);
Finally compare the two timestamps:
if($old_ts - $timestamp > (60*60*48)){
//more than 48 hours
}else{ ... }
I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.
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
}