www.webdeveloper.com
Results 1 to 5 of 5

Thread: Conver date and time to timestamp

  1. #1
    Join Date
    Mar 2009
    Posts
    452

    Conver date and time to timestamp

    hi all, i am trying to convert the date from d/m/Y h:i A (21/12/2011 2:28 AM") to timestamp but no success. i ve also tried strtotime but it returns false not tha timestamp. any suggestion.

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    795
    How about a regular expression?

    Code:
    <?php
    
    	$date = '21/12/2011 2:28 AM';
    
    	if (preg_match('|(\d+)/(\d+)/(\d+) (\d+):(\d+) (\w+)|', $date, $matches)) {
    		$timestamp = mktime(($matches[4] + ($matches[6] === 'PM' ? 12 : 0)) &#37; 24, $matches[5], 0, $matches[2], $matches[1], $matches[3]);
    		echo date('Y/m/d H:i', $timestamp);
    	}
    
    ?>
    Last edited by bionoid; 12-20-2011 at 03:41 PM.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,388
    If using PHP 5.3.0+, you could look at DateTime::createFromFormat() and DateTime::getTimestamp().
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  4. #4
    Join Date
    Mar 2009
    Posts
    452
    let me explain in detail, i have stored transaction time in a field as timestamp using PHP's time() function so that it can be displayed in different date formats. so when i want to search for records after a specific time i need to convert the time entered from a Javascript Datetime picker, and it gives me time like "21/12/2011 12:21 PM", thats what i want to convert to a timestamp and match the records in mysql query

  5. #5
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,388
    My first suggestion would be to see if the Javascript datetime picker can be configured to give a more portable format, e.g. "2011-12-21 15:21", which you could then use directly in your query (properly escaped to avoid SQL injection, of course ). If not, then either look at MySQL's STR_TO_DATE() function, or else see my previous reply for converting it within PHP (assuming a reasonably current version).
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles