简体   繁体   中英

how to extract month and year seperate from a given date in php?

I have a date $da = '18-Nov-2015'

I want month and year separate.I tried this.but it didn't work.

$month  =  date('F',strtotime($da));
$YEAR   =  date('Y',strtotime($da));

Give it try with below code:

$da    =  '18-Nov-2015';
$date  =  DateTime::createFromFormat('d-M-Y',$da);
echo $date->format("Y");
echo $date->format("F");

Note: DateTime We can create the object using arbitrary parameters like $date = DateTime::createFromFormat('dM-Y', $weird_user_input); which can be formatted to unix timestamp or whatever other date format We wish.

You can use the date_parse() function. It returns an array that contains the components of the date: day, month, year, hour, minute, and others.

Usage sample:

$da = '18-Nov-2015';
$dateComps = date_parse($da);
$year = $dateComps['year'];
$month = $dateComps['month'];
$day = $dateComps['day'];
//and so on, ...

Almost you have done.This is how you can do it.

$year = date('Y', strtotime($da));
$month = date('m', strtotime($da));

F - A full textual representation of a month, such as January or March January through December

m - Numeric representation of a month, with leading zeros 01 through 12

M - A short textual representation of a month, three letters Jan through Dec

n - Numeric representation of a month, without leading zeros 1 through 12

Or else simply you can use explode method

$dateArray = explode('-', $da);
$dateArray[0] //date
$dateArray[1] //Month
$dateArray[2] //Year

Date reference : http://php.net/manual/en/function.date.php

use

$da=new DateTime($da);
$da->format('m-d');

hello try this hope you will get your answer what you want. let me know if you got iy correct.

<?php

$dateValue = Date('Y-m-d');
$time=strtotime($dateValue);
$year=date("Y",$time);
$month=date("F",$time);
$date=date("d",$time);

?>

i tried this in http://phpfiddle.org/

$da='18-Nov-2015';
$dateValue = strtotime($da);
$year = date('Y',$dateValue);
$monthName = date('F',$dateValue);
$day = date('d',$dateValue);
echo $monthName;
echo $year;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM