Jump to content

Using Date and Time functions optimally


alexcmm

Recommended Posts

at the end of another post this issue came up so I thought I would start a new topic.

I was told the formula I was using to insert a date wasn't the best. Here's my quote from the other person and my new question:

[quote author=roopurt18 link=topic=115281.msg469701#msg469701 date=1163789828]
Create a DATETIME column in your table.  Store the date as 'YYYY-MM-DD HH:MM:SS' format.  If you are storing the current date and time you can use the MySQL [b]NOW()[/b] function.

When you pull the date out, it will be in 'YYYY-MM-DD HH:MM:SS' format, which may not be what you want to store it in.  You can instead use the MySQL function [b]DATE_FORMAT[/b] to format the date to something else for display purposes.
[/quote]

ok, two questions regarding this. (keep in mind the n00bie classification on the left)

When I send the db the date what should it look like? This is what I have now:
[b]$ud_datemod = (date ("l dS of F Y h:i:s A"));[/b]

And, how do I "pull out the date"? Is that when I'm pulling info from the db? right now what I have is:
[b]$datemod=mysql_result($result,$i,"datemod");[/b]

does this need to be different? sorry I'm asking you to be so literal.
Link to comment
Share on other sites

Store the date as 'YYYY-MM-DD HH:MM:SS' format.
[code]<?php
$sql = "INSERT INTO table (TheDate) VALUES ("
      . "'" . date('Y-m-d H:i:s') . "')";
mysql_query($sql);
?>[/code]
You can store current date and time using the NOW() MySQL function:
[code]<?php
$sql = "INSERT INTO table (TheDate) VALUES (NOW())";
?>[/code]

Pull the date out:
[code]<?php
$sql = "SELECT TheDate AS Unformatted, "
       . "DATE_FORMAT(TheDate, '%a. %b. %D, %Y') AS Formatted "
       . "FROM table WHERE 1";
$q = mysql_query($sql);
if($q){
  while($row = mysql_fetch_array($q)){
    echo '<pre style="text-align: left;">' . print_r($row, true) . "</pre>";
  }
}
?>[/code]
More information on DATE_FORMAT may be found here:
http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.