1

Say I am given a date like "August 2016" is there a way in PHP to simply find if a date has no day given?

All the PHP functions I can find automatically set a "1" to the day of a date if none is given.

What I want to do is weed out dates that don't give me a day.

They are not provided by me, and can be mixed in UK or US formats.

9
  • could you check for a number at the beginning of the string? Commented Aug 22, 2016 at 21:37
  • 1
    Do you expect any other date formats? if so, which ones? Can you control the user input? How do you get the values? Please clarify your question so we can help you properly. Commented Aug 22, 2016 at 21:39
  • All the PHP functions I can find automatically set a "1" to the day of a date if none is given. just use a DateTime for that, then set the day manually. what day do you expect if none is given? you can just load it into DateTime and ignore the date, you can control whatever you format output after that anyway Commented Aug 22, 2016 at 21:40
  • 1
    update was not a great help to be honest. source of date? range of possible date formats? use of date? what will you do if it has a day? does not have a day? Commented Aug 22, 2016 at 21:51
  • 1
    great, next time better question please Commented Aug 22, 2016 at 21:56

1 Answer 1

3

You can try using DateTime::createFromFormat()

$notValid = DateTime::createFromFormat('F Y', '21 January 2016'); // false
$valid = DateTime::createFromFormat('F Y', 'January 2016'); // DateTime object
Sign up to request clarification or add additional context in comments.

4 Comments

no need for createFromFormat, even the constructor can understand August 2016
@Ghost indeed, you're right, but author of the question wanted to verify if given date has or has not day given. Both August 2016 and 21 August 2016 will return true, which not what he needs.
This looks indeed like a nice approach. I would suggest you would turn that into a function that takes a date string and returns the day number if present, and null otherwise.
This is EXACTLY what I needed, it works perfectly to weed out dates that don't give me a day thank you! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.