SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Jan 2012
    Posts
    254
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Formatting Dates

    I have a field named Born, in the date format. After my query, I display a value from the field...

    Code:
     $Born = $row['Born'];
     echo $Born;
    It displays 1955-01-07, which is exactly what's in the database. However, I want to format it to display Jan. 7, 1955. So I checked the PHP Manual, and it looks like I'm supposed to do something like this...

    Code:
     $Born = $row['Born'];
     $Born = date("F j, Y");
     echo $Born;
    However, my solution displays August 11, 2013, which isn't even in my database.

    Can anyone tell me what I'm doing wrong? Thanks.

  2. #2
    SitePoint Mentor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,257
    Mentioned
    32 Post(s)
    Tagged
    5 Thread(s)
    Hi Chavista,

    The date function returns the current system date in the format you specify, unless you provide a timestamp as the second argument.

    You can use PHP's DateTime class to get the result you want:
    PHP Code:
    $Born = new DateTime($row['Born']);
    echo 
    $Born->format("M. j, Y"); 

  3. #3
    Barefoot on the Moon! silver trophy
    Force Flow's Avatar
    Join Date
    Jul 2003
    Location
    Northeastern USA
    Posts
    4,524
    Mentioned
    51 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by Chavista View Post
    However, my solution displays August 11, 2013, which isn't even in my database.

    Can anyone tell me what I'm doing wrong? Thanks.
    When you use the date() function, the current date & time are automatically supplied if you don't specify a specific date/time.

    http://php.net/manual/en/function.date.php

    However, using the date() function based on the UNIX timestamp is a little out of date now. It's better to use the DateTime class.

    PHP Code:
    $Born $row['Born'];
    $BornDate DateTime::createFromFormat('Y-m-d'$Born);
    echo 
    $BornDate->format('M j, Y'); 
    Or, if you prefer the procedural code style instead of the object-oriented code style:
    PHP Code:
    $Born $row['Born'];
    $BornDatedate_create_from_format('Y-m-d'$Born);
    echo 
    date_format($BornDate'M j, Y'); 
    http://www.php.net/manual/en/datetim...fromformat.php
    Visit The Blog | Follow On Twitter
    301tool 1.1.5 - URL redirector & shortener (PHP/MySQL)
    Can be hosted on and utilize your own domain

  4. #4
    SitePoint Addict
    Join Date
    Jan 2012
    Posts
    254
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That works great; thanks.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •