A simple question: how to divide the date (17-17-2011) by month, day, year? Php

I have a variable called $ orderdate, and it is set to a date format such as mm-dd-yyyy.

In PHP, how would I split this variable into $ month, $ day, $ year?

Thanks for your help.

+7
source share
5 answers

If you are confident in the format of the input value, then:

$orderdate = explode('-', $orderdate); $month = $orderdate[0]; $day = $orderdate[1]; $year = $orderdate[2]; 

You can also use preg_match() :

 if (preg_match('#^(\d{2})-(\d{2})-(\d{4})$#', $orderdate, $matches)) { $month = $matches[1]; $day = $matches[2]; $year = $matches[3]; } else { echo 'invalid format'; } 

Alternatively, you can use checkdate() to confirm the date.

+17
source

If you don’t know "β†’ about the input format, you can also do the following:

 $time = strtotime($input); $day = date('d',$time); $month = date('m',$time); $year = date('Y',$time); 
+15
source
 list($month, $day, $year) =explode("-",$orderdate); 
+4
source

Use explode to split the string

 list($m,$d,$y)=explode('-',$date); 
+2
source

A good approach is to use date_parse_from_format () .

In your example:

 $dateStr = '03-27-2015'; $dateArray = date_parse_from_format('md-Y', $dateStr); 

This gives $dateArray like:

 Array ( [year] => 2015 [month] => 3 [day] => 27 [hour] => [minute] => [second] => ... ) 
+2
source

Source: https://habr.com/ru/post/895306/


All Articles