Fastest way to get month, day, year, from date string - php

I am getting a date from the mysql database:
here is what it comes out as:
2017-01-20
what would be the fastest way to get the month, day, and year, so for example, when i echo, it will be like this:
echo $month; //01
echo $day; //20
echo $year; //2017

Well, if you know that the output will consistently be a string in the format "YYYY-MM-DD", the most basic approach is:
<?php
$query = ... //query is your string "YYYY-MM-DD"
$year = substr($query, 0, 4);
$month = substr($query, 5, 2);
$day = substr($query, 8, 2);
echo $month;
echo $day;
echo $year;
?>

Let's assume you have that string in a variable called $date
$date = '2017-01-20';
You can explode it into a list if you are sure the format is consistent:
list($year, $month, $day) = explode("-", $date, 3);
You could convert the date to a time integer using strtotime to use in other functions like date. This has the added benefit of being able to test that this is a well-formed date:
$time = strtotime($date);
if ($time === false) die("Bad date format: $date.");
$year = date('Y', $time);
$month = date('m', $time); // 'n' if you don't want leading zero
$day = date('d', $time); // 'j' if you don't want leading zero
As jasonmoqio points out, since you asked for fastest, substr is a tiny bit faster than exploding. (On my workstation looping substr vs. explode 10 million times only produced an improvement of 1/1000th of a second over exploding, so unless this is in a loop that gets run millions of times, you will not notice the difference and should opt for code readability.)
$year = substr($date, 0, 4);
$month = substr($date, 5, 2);
$day = substr($date, 8, 2);

Try this:
$date = new DateTime('2017-01-20');
echo 'Year:'.$date->format("Y");
echo 'Month:'.$date->format("m");
echo 'Day:'.$date->format("d");
Output:
Year: 2017
Month: 01
Day: 20

If you want to quickly get the date from mysql, try using regex like this.
if (preg_match('/^(?P<year>\d+)[-\/](?P<month>\d+)[-\/](?P<day>\d+)$/', $your_date, $matches)) {
$mydate = $matches['year'] . "-" . $matches['month'] . "-" . $matches['day'];
$whatever = date('Y-m-d', strtotime($tgl));
// You can echo it...
// echo $matches['year'];
// echo $matches['month'];
// echo $matches['day'];
}
Hope this help you out. :D

Related

PHP get the year from the variable

I usually mess this up, but I am trying to get a year from a variable $date = 2011-01-01 I am trying to get 2011 from the variable...I tried this but it didnt echo anything out...
date(strtotime("Y"), strtotime($date));
$year = date('Y', strtotime('2011-01-01'));
Or, if you don't want to convert to date, and trust your input format:
$year = explode('-', '2011-01-01')[0];
The above requires PHP 5.4, on older versions you need two lines:
$arr = explode('-', '2011-01-01');
$year = $arr[0];
Or yet, this slightly faster alternative suggested by tigrang:
$year = substr($date, 0, 4);
Or, an even faster way, as salathe suggested:
$year = (int) $date;
(everything after the first dash will be ignored, so $year will contain an integer with the year part of the date (unlike the other options, where $year would be a string).
date('Y', strtotime($date)) should do
First arg is the format, second is timestamp.
You can explode the date into a list and call each date item individually.
$date = '2012-01-01';
list($year, $month, $day) = explode('-', $date);
echo $year; // echoes 2012
May I suggest using PHP's DateTime class as an alternative:
$date = '2011-01-01';
$dateTime = new DateTime($date);
echo $dateTime->format('Y');
DateTime is all well and good, but lets go old school.
sscanf($date, '%d', $year);
// or
$year = strtok($date, '-');
// or
$year = substr($date, 0, 4);
// or
$year = (int) $date;
or, putting the sensible hat back on, you could use DateTime or correctly use date().
$datetime = new DateTime($date);
$year = $datetime->format('Y');
// or
$year = date('Y', strtotime($date));

How can I convert date from 8 to AUG

I would like to convert the number to actual month. I only need a month.
I am now trying like this
$str = 8;
$anInt = intval($str);
$test = date('M',$anInt);
echo $test;
the result is JAN, I was supposed to get "AUG" as a result. I dont know why.
any idea or suggestion for me?
The date() function assumes a timestamp.
You should try this:
$test = date('M',mktime(0,0,0,$anInt,0,0);
From the docs for date and mktime:
// Prints: Your date's month is : August
echo "Your date's month is : " . date("F", mktime(0, 0, 0, $anInt, 0, 0));
Use mktime.
echo date('M', mktime(0, 0, 0, $str));
Here you are:
echo date('M',strtotime('08/01/2012'));
Or, if you want all caps:
echo strtoupper(date('M',strtotime('08/01/2012')));
There might be other approaches to this, but this was the first to come to mind
Duplicate question. Read here.
Read about date function here.
using date() you should use timestamp.
To convert date value to timestamp, use strtotime
$date = '2012-8-8';
$timestamp = strtotime($date);
echo date('M',$timestamp);
For your problem:
$monthnumber = 4;
$date = '2012-'.$monthnumber.'-8';
$timestamp = strtotime($date);
echo date('M',$timestamp);

convert a date in this format '031012' into a date that I can add days to

I have a date in this format 030512 (ddmmyy).
But I'm having trouble with converting this to a date usable format I can add days to.
Basically.. I extracted the date above from a text file, Now I need to be able to add a number of days to it. But I am having trouble parsing the date in this format.
Is there another way of doing this rather then something like this:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
$date_after = $day . "-" . $month . "-".$year;
// Now i need to add x days to this
$total_no_nights = 010; // must be this format
$days_to_add = ltrim($total_no_nights,"0"); // 10, remove leading zero
// how do i add 10 days to this date.
You can do this (php >= 5.3):
$date = DateTime::createFromFormat('dmy', '030512');
$date->modify('+1 day');
echo $date->format('Y-m-d');
http://www.php.net/manual/en/datetime.createfromformat.php
For php < 5.3 :
$dateArray = str_split('030512', 2);
$dateArray[2] += 2000;
echo date("d/m/Y", strtotime('+1 day', strtotime(implode('-', array_reverse($dateArray)))));
try this using the month/day/year you already have:
$date = "$month/$day/$year";
$change = '+10 day';
echo date("d/m/Y", strtotime($change, strtotime($date)));
Assuming the date will always be in the future (or at least after 1st Jan 2000), you're not far wrong:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
// dd-mm-yy is not a universal format but we can use mktime which also gives us a timestamp to use for manipulation
$date_after = mktime( 0, 0, 0, $month, $day, $year );
// Now i need to add x days to this
$total_no_nights = "010"; // must be this format
$days_to_add = intval( $total_no_nights ); // No need to use ltrim
// Here's the "magic". Again it returns a timestamp
$new_date = strtotime( "+$days_to_add days", $date_after );
Using the DateTime object would be easier but you say you're not on PHP5.3.
You can't do date manipulation with strings becase, well, they are not dates. In PHP, you can use Unix timestamps (which are actually integers...) or DateTime objects. In you case:
$timestamp = strtotime('-10 days', mktime(0, 0, 0, $month, $day, $year));
echo date('r', $timestamp);
... or:
$object = new DateTime("$year-$month-$day");
$object->modify('-10 days');
echo $object->format('r');
Also, please note that 010 is an octal number that corresponds to 8 in decimal.
using the convert function in sql the date can be obtained in appropriate format.
anter that operations can be performed in php to manipulate the date. i hope that answers your query.

Getting a list of last day of month dates in PHP

These answers don't quite do what I want:
Getting last month's date in php
How to find the last day of the month from date?
I have the following code that is meant to print a select-box with all the last day of month dates from a given date:
$last_case_date = $this->query_end_date();
$increm_date = "2011-06-01";
echo '<select name = "end_interval">';
$increm_date = date('Y-m-d', strtotime("$increm_date"));
while($increm_date <= $last_case_date) {
// next date is $increm_date + 1 month
$increm_date = date('Y-m-d', strtotime("$increm_date + 1 months"));
// then we want the last day of this new date
$month = substr($increm_date, 5, 2);
$year = substr($increm_date, 0, 4);
$increm_date = $this->last_day_of_month($month, $year);
echo '<option value = "'.$increm_date.'" selected = "selected"'.'>'.$increm_date.'</option>';
}
echo '</select>';
where last_day_of_month is this:
function last_day_of_month($month = '', $year = '') {
if(empty($month)) {
$month = date('m');
}
if(empty($year)) {
$year = date('Y');
}
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 months', $result));
return date('Y-m-d', $result);
}
which I borrowed from here.
Strange thing that happens is that I get these dates:
2011-07-31
2011-08-31
2011-10-31
but no 2011-09-30 ! It probably has something to do with September only having 30 days or something right?
Can anyone spot the problem? I've been staring at it for ages.... Thank you :).
You could just use the built in function for php
date('t', $timestamp);
So your function would look like:
function last_day_of_month($month = '', $year = '') {
$month
|| $month = date('m');
$year
|| $year = date('y');
$timestamp = mktime(0, 0, 0, $month, 1, $year);
return date('Y-m-t', $timestamp);
}
To get the last day of the month, use:
date('Y-m-t', strtotime("$year-$month-01"))
't' stands for the "number of days in the given month", i.e. for the last day. No need to add and subtract anything.
The below will output a select box with options for the last day of each month in the current year:
echo "<select>";
for($i=1;$i<=12;$i++){
echo "<option>".date('Y-m-t', strtotime(date("Y")."-".$i."-01"))."</option>";
}
echo "</select>";
If you want to set to a different year, simply replace date("Y") with, say, "2010". You could, for example loop through a number of years, running the code to output the options for each.
I think this is the problem of your piece of code:
the original $increm_date is "2011-06-01";
a a certain point in the while cycle $increm_date is 2011-08-31 (last day of august)
the in the cycle you add a month so $increm_date is 2011-10-01 (first day of october, NOT THE LAST OF SEPTMEBER) so you call the last_day_of_month providing OCTOBER NOT SEPTEMBER.
I am not sure of this. To test try to print the $increm_date before last_day_of_month is called

Using PHP date to display weekly dates

I'm not really sure what to call this. But basically I want to be able to have a user click on "Popular Stories from This Week", and it will take them to a page that will have other stuff but mainly the dates. For example, July 10-17.
I'm currently using this code:
$seven_days_ago = date('j') - 7;
$time_span = date('F ' . $seven_days_ago . ' - j');
Now, I ran into a problem when we entered July, because it would display something like July -3 - 4. I need a way for it to detect if the seven days ago variable is negative, and figure out what it should display. Help?
Thanks!
You can use strtotime for this:
$seven_days_ago = strtotime('-7 days');
$time_span = date('F j', $seven_days_ago) . ' - ' . date('F j');
The above gives me "June 28 - July 5" for $time_span.
you need to use strtotime
$timeago = strtotime("7 days ago");
What about using
$unix_timestamp = mktime(0, 0, 0, date("m"), date("d")-7, date("Y"));
and just take the returned unix timestamp?
Update
Just a little code snipped that will give you a full working example. However I don't like it that much :)
<?php
$today = date("d F");
list($today_day, $today_month) = explode(" ", $today);
$previous = date("d F", mktime(0, 0, 0, date("m"), date("d")-7, date("Y")));
list($previous_day, $previous_month) = explode(" ", $previous);
if($today_month != $previous_month){
echo $previous_month." ".$previous_day." - ".$today_month." ".$today_day;
}else{
echo $today_month." ".$previous_day." - ".$today_day;
}
die();
?>
i just created a very nifty little function. Just pass it the Week number, it returns you an array of that week's days dates.
function findWeekDates($weekNumber=null, $year=null ) {
// receives a specific Week Number (0 to 52) and returns that week's day dates in an array.
// If no week specified returns this week's dates.
$weekNumber = ($weekNumber=='') ? date('W'): $weekNumber ;
$year = ($year=='') ? date('Y'): $year ;
$weekNumber=sprintf("%02d", $weekNumber);
for ($i=1;$i<=7;$i++) {
$arrdays[] = strtotime($year.'W'.$weekNumber.$i);
}
return $arrdays;
}
Example Usage - find a given week start and end dates:
$week= (isset($_GET['week']) && $_GET['week'] !=='')? $_GET['week'] : date('W') ;
$year = (isset($_GET['year']) && $_GET['year'] !=='')? $_GET['year'] : date('Y') ;
if($week>52) {
$week = 1;
$year++;
}else if($week<1) {
$week=52;
$year--;
}
$week_days = findWeekDates($week, $year);
$starting_date = date('Y-m-d', $week_days[0]);
$ending_date = date('Y-m-d', $week_days[6]);
hope this helps...

Categories