开发者

Split string from a date

I want split a string using PHP to get a individual date info.

For example:

$date = '08/05/2010';

would create the varables

$month = '08';

$day = '05';

$year = '2010';

Thank y开发者_运维技巧ou.


Use explode:

$date = '08/05/2010';
list($month, $day, $year) = explode('/', $date);


if that's your example, you could explode it into an array.

$array = explode('/', $date);


list($month, $day, $year) = explode('/', $date);


Assuming it's always in that format, you want explode:

<?php

    $date = '08/05/2010';

    $arr = explode("/", $date);

    list($month, $day, $year) = $arr;

    // $month = 08, $day = 05, $year = 2010.

?>


The answers posted above would do the trick. You probably also want to check the date conforms to your expected format before you run your function. The checkdate function would be useful for this, or this snippet is a standalone implementation.


I agree with the comments about using the checkdate function, however that is really for after you split the date apart because you pass in each part (month, day, year) to check.

If you are getting the original date from user input you might want to make sure that you are getting the right format before you separate it out (using list or explode as shown previously.)

I see two options for validity if it is coming from a user: first is to only allow them to select the date, and not freely enter it. The second is to make sure you are getting it in the mm/dd/yyyy format you are expecting. You could perform a regular expression match on it before the separation. The regular expression could be something like /\d{2}/\d{2}/\d{4}/

Anyway, not really needed if you are sure of your source, but it is always important to think of where your data is coming from and how clean it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜