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);

Related posts

Leave a Reply

2 comments

  1. 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
    
  2. 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