Jump to content

Changing the format of the date


McMaster

Recommended Posts

Hey,

 

I have a database with a date field that has the date in this format:

 

August 2, 2010 11:04 pm

 

I was wondering if it was possible to change this so I have the day, month and year in separate variables like this:

 

$day = "2";

$month = "8";

$year = "2010";

 

Also notice how I have changed August to "8". I was wondering if there was an easy way around getting this done?

 

Thanks in advance

Link to comment
Share on other sites

You can convert the above string into date format by using the below query:-

 

select str_to_date('August 2, 2010 11:04 pm','%M %e, %Y %h:%i %p');

 

output is 2010-08-02 23:04:00

 

 

Now you can apply other date functions on this to get the desired result. For eg.

 

select Month(str_to_date('August 2, 2010 11:04 pm','%M %e, %Y %h:%i %p')), day(str_to_date('August 2, 2010 11:04 pm','%M %e, %Y %h:%i %p')), year(str_to_date('August 2, 2010 11:04 pm','%M %e, %Y %h:%i %p'))

 

This will give the desired output of month=8, day=2 and year=2010

Link to comment
Share on other sites

Thanks for your response. The thing is, the date is contained within 1 table field only. So Would I do something like:

 

$sql = mysql_query = ("select Month(str_to_date(date,'%M %e, %Y %h:%i %p')), day(str_to_date(date,'%M %e, %Y %h:%i %p')), year(str_to_date(date,'%M %e, %Y %h:%i %p')) from recent_activity");

 

Also, this may sound silly but how exactly do I extract the month, day and year from that query? Would I just use something like mysql_result($sql)?

 

Thanks

Link to comment
Share on other sites

You would better off using a correct DATE or DATETIME data type to store your information in the table (that's what the DATE or DATETIME data types are for.)

 

The second query that Vikas Jayna posted does get the three pieces of information you asked about, using the mysql MONTH(), DAY(), and YEAR() functions in the query. I would use alias names for each part so that it is simpler to reference them when you retrieve the data in your php code.

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.