1

I have to convert a string input to date "1990/07/22" to 22/07/1990 as date,My function is as follows as:

public function($date){
    $date_format_sec = strtotime($date);
    $date_of_birth = new \DateTime('@'.$date_format_sec);
}

It uploads date as 21/07/1990 since I didn't give time.How to get the exact date given as same as input.

1
  • You don't need to use strtotime($date) if $date is a valid date string, you can pass this on the constructor of DateTime and then format it to whatever you want. Commented Aug 16, 2018 at 8:20

4 Answers 4

2

You can format your date with php

$formatedDate = $date_of_birth->format('d-m-Y');

Documentation

Sign up to request clarification or add additional context in comments.

Comments

2
    $input = '1990/07/22';
    $date = \DateTime::createFromFormat('Y/m/d', $input)->format('d-m-Y');

Comments

1

As I said, you don't need to use strtotime, if the $date string is a valid date, the class DateTime will read it. After that you can use format.

In this example I set the format to be always the one you expect, while you can put any other format accepted by it.

public function getMyDate($date, $format = 'd/m/Y') {
    $date_of_birth = new \DateTime($date);

    return $date_of_birth->format($format);
}

Comments

-2
    public function formatDate($date) {return date('d/m/Y', strtotime($date));}

2 Comments

he's using a DateTime object... why would you go to strtotime if you have the object?
Although this code might (or might not) solve the problem, a good answer should always explain how the problem has been solved and what the code does.

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.