get day from date in php - php

I have the code below which I got from the php: mktime manual just edited it to use my own variables but for the day I always get "1".
$requested_day = $_GET['day'];
$requested_month = $_GET['month'];
$requested_year = $_GET['year'];
if (!empty ($requested_day) || empty ($requested_month) || empty ($requested_year))
{
echo $requested_day. " ".$requested_month." ".$requested_year." is on day : ". date("1", mktime(0, 0, 0, $requested_month, $requested_day, $requested_year));
}
I enter the values and it is outputted as:
23 09 2010 is on day : 1
I think I am having a problem on the "1" I entered on the date, I don't quite understand what this is actually for?
Thanks

Your format string should have a lower case L not a number one.
date("l", mktime(...
The "l" in the format string says to show the day of the week.

Brace yourself:
1 != l (the latter is a lower-case L)

Related

PHP DATE ignoring day number 'z' and jumps to ELSE

I'm trying to piece together a script that will output a unique message every day of the year, so obviously this would be 365 messages. The code that I'm testing sadly jumps straight to else, rather than respecting the date 'z'. I suspect that it’s a problem with my code, here’s what I've attempted so far:
<?php
$date = date('z');
if($date == "41"){
echo "Test Message One";
}
elseif($date == "42"){
echo "Test Message Two";
}
else{
echo "Sadly your script does not work";
}
?>
Please note that date('z') is indexed at 0 instead of 1 (as I learned the hard the way). You will have to add +1 to your day of the year.
$date = date('z') + 1;
There is nothing wrong with the code as such but more so with the assignment of the day numbers within the code, thanks to Michael Berkowsk, Mark Baker and putvande for pointing this out. Rather than calculating the day numbers you need in your head it's advisable to use Google or epoch day numbers.
Notably it's important to note that php date starts from 0 to 365, this means:
Jan 1st = 0
Jan 2nd = 01
If your want to Jan 1st = 1, Jan 2nd = 2 and so forth simply edit your code to look something like this:
$date = date('z') + 1; credit to Err for this.

PHP convert 2 digit year to a 4 digit year

I have data coming from the database in a 2 digit year format 13 I am looking to convert this to 2013 I tried the following code below...
$result = '13';
$year = date("Y", strtotime($result));
But it returned 1969
How can I fix this?
$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y'); // output: 2013
69 will result in 2069. 70 will result in 1970. If you're ok with such a rule then leave as is, otherwise, prepend your own century data according to your own rule.
One important piece of information you haven't included is: how do you think a 2-digit year should be converted to a 4-digit year?
For example, I'm guessing you believe 01/01/13 is in 2013. What about 01/01/23? Is that 2023? Or 1923? Or even 1623?
Most implementations will choose a 100-year period and assume the 2-digits refer to a year within that period.
Simplest example: year is in range 2000-2099.
// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;
What if we want a different range?
$baseyear = 1963; // range is 1963-2062
// this is, of course, years of Doctor Who!
$shortyear = 81;
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
Try it out. This uses the modulo function (the bit with %) to calculate the offset from your base year.
$result = '13';
$year = '20'.$result;
if($year > date('Y')) {
$year = $year - 100;
}
//80 will be changed to 1980
//12 -> 2012
Use the DateTime class, especially DateTime::createFromFormat(), for this:
$result = '13';
// parsing the year as year in YY format
$dt = DateTime::createFromFormat('y', $result);
// echo it in YYYY format
echo $dt->format('Y');
The issue is with strtotime. Try the same thing with strtotime("now").
Simply prepend (add to the front) the string "20" manually:
$result = '13';
$year = "20".$result;
echo $year; //returns 2013
This might be dumbest, but a quick fix would be:
$result = '13';
$result = '1/1/20' . $result;
$year = date("Y", strtotime($result)); // Returns 2013
Or you can use something like this:
date_create_from_format('y', $result);
You can create a date object given a format with date_create_from_format()
http://www.php.net/manual/en/datetime.createfromformat.php
$year = date_create_from_format('y', $result);
echo $year->format('Y')
I'm just a newbie hack and I know this code is quite long. I stumbled across your question when I was looking for a solution to my problem. I'm entering data into an HTML form (too lazy to type the 4 digit year) and then writing to a DB and I (for reasons I won't bore you with) want to store the date in a 4 digit year format. Just the reverse of your issue.
The form returns $date (I know I shouldn't use that word but I did) as 01/01/01. I determine the current year ($yn) and compare it. No matter what year entered is if the date is this century it will become 20XX. But if it's less than 100 (this century) like 89 it will come out 1989. And it will continue to work in the future as the year changes. Always good for 100 years. Hope this helps you.
// break $date into two strings
$datebegin = substr($date, 0,6);
$dateend = substr($date, 6,2);
// get last two digits of current year
$yn=date("y");
// determine century
if ($dateend > $yn && $dateend < 100)
{
$year2=19;
}
elseif ($dateend <= $yn)
{
$year2=20;
}
// bring both strings back into one
$date = $datebegin . $year2 . $dateend;
I had similar issues importing excel (CSV) DOB fields, with antiquated n.american style date format with 2 digit year. I needed to write proper yyyy-mm-dd to the db. while not perfect, this is what I did:
//$col contains the old date stamp with 2 digit year such as 2/10/66 or 5/18/00
$yr = \DateTime::createFromFormat('m/d/y', $col)->format('Y');
if ($yr > date('Y')) $yr = $yr - 100;
$md = \DateTime::createFromFormat('m/d/y', $col)->format('m-d');
$col = $yr . "-" . $md;
//$col now contains a new date stamp, 1966-2-10, or 2000-5-18 resp.
If you are certain the year is always 20 something then the first answer works, otherwise, there is really no way to do what is being asked period. You have no idea if the year is past, current or future century.
Granted, there is not enough information in the question to determine if these dates are always <= now, but even then, you would not know if 01 was 1901 or 2001. Its just not possible.
None of us will live past 2099, so you can effectively use this piece of code for 77 years.
This will print 19-10-2022 instead of 19-10-22.
$date1 = date('d-m-20y h:i:s');

Numeric value of Months in PHP

Im trying to display my Date field from my MySQL database.
format is 2012-01-01 to 2012-01-31
Is there a way to display the month of January to 0 instead of 1?
I used strtotime to change its format
date('Y, n, j',strtotime($s['date']))
but this showed
2012, 1, 1
I want to display this as
2012, 0, 1
You can always do something like:
$time = strtotime($s['date']);
$str = date('Y, ', $time);
$str .= intval(date('n', $time)) - 1;
$str .= date(', j', $time);
Not sure this is the best/only way, but it should work.
EDIT: davidethell's point taken, code changed accordingly. +1 for the comment.
Or you could use getdate() instead of date() to return the date as an array, and then concatenate the required values eg.
<?php
$date = getDate(strtotime($s['date']));
echo $date['year'].', '.($date['mon']-1).', '.$date['mday'];
?>
If you prefer you can do it in SQL:
SELECT MONTH(my_date_col) - 1 AS custom_month_col;
Otherwise I agree with #Ynhockey
Edited (see comment):
SELECT CONCAT(YEAR('2012-03-08'),'-', (MONTH('2012-03-08') - 1), '-', DAY('2012-03-08')) AS custom_month_col;
In case you only need the month output, this worked for me:
$month = intval(date('n',strtotime($result["Date"]))) - 1;
$result["Date"] is how the value passed from MySQL is called.

find if the date containd a valid format using a preg_match

I have 1 text input box so user can enter a date in the following format (i don’t want to use 3 separate input boxes for the month, date and year) :
mm/dd/yyyy (could be a single digit m/d/yyyy)
or
mm-dd-yyyy (single digit m-d-yyyy)
I then want to use preg_match to check if the user entered a value according to the format above. If yes, i will extract the month, day and year (using substr) and use php function checkdate() to check for a valid date, know when it’s a leap year and prevent mistakes such as September 31...
Hopefully, i’m not missing anything...
Right now, im stuck in trying to figure out how to use preg_match to check if the user has entered a valid date according to the format indicated above
this is what i’ve came up with... ???
preg_match(d{2})(\d{2})(\d{4})
extracting the month , day and year (looks ok to me):
$date = trim($_POST['date']);
$month = substr($date, 0, 2);
$day = substr($date, 3, 2);
$year = substr($date, 6, 4);
and finally , check the date is valid (looks ok to me):
checkdate($month, $day, $year);
Thanks
You could use something like this:
if (preg_match("#^(\d{1,2})\D(\d{1,2})\D(\d{2,4})$", trim($date), $match)
and checkdate($match[2], $match[1], $match[3])) {
$timestamp = mktime(0, 0, 0, $match[2], $match[1], $match[3]);
echo "Date is valid";
} else
echo "Invalid date";
The only issue I see here is if user inputs something like 06.01.12 expecting your system to guess 2012, when checkdate will think of the year 12. You can't just add "20" at the start of the string, since another user may input something like 15.11.99 expecting a 1999 guess. This could be solved by a readonly field with javascript-based calendar, which will force correct date format, which you can then simply explode("-", $date) without using regexp.

PHP: date function to get month of the current date

I want to be able to figure out the month of the current date variable. I'm ex vb.net and the way to do it there is just date.Month. How do I do this in PHP?
Thanks,
Jonesy
I used date_format($date, "m"); //01, 02..12
This is what I wanted, question now is how do I compare this to an int since $monthnumber = 01 just becomes 1
See http://php.net/date
date('m') or date('n') or date('F') ...
Update
m Numeric representation of a month, with leading zeros 01 through 12
n Numeric representation of a month, without leading zeros 1 through 12
F Alphabetic representation of a month January through December
....see the docs link for even more options.
What does your "data variable" look like? If it's like this:
$mydate = "2010-05-12 13:57:01";
You can simply do:
$month = date("m",strtotime($mydate));
For more information, take a look at date and strtotime.
EDIT:
To compare with an int, just do a date_format($date,"n"); which will give you the month without leading zero.
Alternatively, try one of these:
if((int)$month == 1)...
if(abs($month) == 1)...
Or something weird using ltrim, round, floor... but date_format() with "n" would be the best.
$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime);
echo date('y', $unixtime );
as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so
echo date('n'); // "9"
As it's not specified if you mean the system's current date or the date held in a variable, I'll answer for latter with an example.
<?php
$dateAsString = "Wed, 11 Apr 2018 19:00:00 -0500";
// This converts it to a unix timestamp so that the date() function can work with it.
$dateAsUnixTimestamp = strtotime($dateAsString);
// Output it month is various formats according to http://php.net/date
echo date('M',$dateAsUnixTimestamp);
// Will output Apr
echo date('n',$dateAsUnixTimestamp);
// Will output 4
echo date('m',$dateAsUnixTimestamp);
// Will output 04
?>
To compare with an int do this:
<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
echo "They are the same";
}
?>

Categories