dotnetdevcsharp
dotnetdevcsharp

Reputation: 3980

current date as date object

I am tryng to take away current date from a date stored in db of wordpress but it is a string i am finding hard to understand how to make a date object so i can do diff of it like this.

$dateJoined=the_field('date_joined', $post_id );
$dateJoined=the_field('expirey_date', $post_id );
$currentDate =  new DateTime(date('m/d/Y h:i:s a', time())0;
$dateJoined = new DateTime($dateJoined);
$expiredate = new DateTime($expiredate);

I want to take the date from current date and get the number of days till their option will expire

$diff = $currentDate->diff($expiredate);

Upvotes: 1

Views: 43

Answers (2)

Marwelln
Marwelln

Reputation: 29413

To get the current date, just use new DateTime, you don't need to use arguments in the constructor.

If you want to create a DateTime object from a string and you know the format, use the createFromFormat method.

$dateJoined = DateTime::createFromFormat("m/d/Y", "06/02/2016");
$dateExpired = DateTime::createFromFormat("m/d/Y", "06/10/2016");

To get the days between two dates you use the diff method as you said in the first post.

$diff = $dateJoined->diff($dateExpired);
echo $diff->days; // 8

Upvotes: 1

Himanshu Sundariyal
Himanshu Sundariyal

Reputation: 125

Please check the below code

$dateJoined=the_field('date_joined', $post_id );
$expiredate=the_field('expirey_date', $post_id );
$dateJoined = date("m/d/y", strtotime($dateJoined));
$expiredate = date("m/d/y", strtotime($expiredate));
$currentDate =  date("d-m-Y");
$dateJoined = strtotime($dateJoined);
$expiredate = strtotime($expiredate);
$diff = date_diff($currentDate, $expiredate);

it will help you

Upvotes: 0

Related Questions