Jump to content

PHP date


gary00ie

Recommended Posts

Hi,

 

I need a fast function to extract the year (YYYY) from a string.

 

The string will be YYYY-MM-DD or DD-MM-YYYY.

Would a regular expression help with this?  Maybe something like:

echo preg_match($dateStr);

 

Any help would be appreciated.  I'm getting nowhere with this.

Thanks in advance :)

Link to comment
Share on other sites

There may be a way to do this with a regular expression but I have no clue how to do that so I would do something like this..

 

<?php

//this case would be MM-DD-YYYY
if ((strpos($dateStr, "-") == 2) && (strrpos($dateStr, "-") == 5)
     //then strip off the last 4 characters

//this case would be YYYY-MM-DD
else if ((strpos($dateStr, "-") == 4) && (strrpos($dateStr, "-") == 7)
     //then strip off the first 4 characters

?>

 

would this work?

Link to comment
Share on other sites

Thank you both for the replies.

 

So could I have - as the delimiter also?

$dateStr = '2010/11/11';  // or 2010-11-11 
echo preg_match('/\d{4}/', $dateStr, $matches);

Also, $dateStr could also be: DD-MM-YYYY also, correct?

 

All of those are correct.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.