Is it possible to change the current 24 hr format like 22:16:08 to something like 10:16:08 in mysql?
I want to change how these values are saved. Is it possible or I will just let php handle things for me?
Don't change the way how these values are saved. Change the way they are output.
See TIME_FORMAT()
In your case, this would show a TIME field as 10:16:08 PM:
SELECT TIME_FORMAT(timefield, "%l:%i:%s %p") AS date_formatted;
You should always store date/time values in their native format, which in MySQL is the 24hr format. You can change how they're retrieved with
SELECT DATE_FORMAT(somedatetimefield, 'format string here')
FROM table
where the format string options are defined here
If doing that manually for every query is a problem, you can always create a view to do it for you automatically.
You really shouldn't change how the data is saved in MySQL. Instead you should only present it differently. You can use PHP's date function to format the date in anyway you want. This is a huge advantage because you are separating how the data is saved and how the data is presented.
Using DATEFORMAT you can save/fetch the date how you wish (much like PHP date()'s syntax)
Like Pekka said: Don't change the way how these values are saved.
You can also easily handle this in php using date()
like date("hh:ii:ss")
This puts out the format you used in your example. (which is 12-hours format and leading zeros.)
Related
I am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.
I have a DB table with relation 1: N where N represents multiple dates for one event. The column with the dates is DateTime type, and I would like to keep the Time option for later use, but it won't be so bad if I have to change it to Date type.
The problem comes when I have to show those multiple dates in some GUI. I get the dates with the GROUP_CONCAT function which means that in JavaScript I operate with a string with comma-separated values representing the different dates, which by now is in the default SQL DateTime format - YYYY-mm-dd hh:mm:ss.
I use the split(',') function to get each date-time value and what I can do is to change the type of the SQL column to Date so when I split the string in JavaScript to end up with YYYY-mm-dd values. Which should be reversed to dd-mm-YYYY for the GUI.
I'm not sure how to proceed here. I have in mind two main options:
First: Maybe there's a way to use dd-mm-YYYY format in SQL which will solve all the problems.
Second: some kind of (complex?!?) String manipulation in JavaScript to split the string of dates into an array with multiple elements and then try to format each element the way I need.
Honestly - I want to avoid the second option, but don't know if the first is possible, and maybe, there's another way that I haven't think of.
Try this..
SELECT GROUP_CONCAT(DATE_FORMAT( date_time_column, '%d-%m-%Y' )) FROM test_table;
First of all I advise to use the native Date/DateTime-format everywhere in your code and only use localized variations like dd-mm-yyyy only where you really want to display it. First reason: it is consistent in your code. Second reason: Sorting.
Example:
2012-03-01 > 01-03-2012
2012-05-12 > 12-05-2012
2012-01-03 > 03-01-2012
Sorted by the native format you'll get...
1: 2012-01-03
2: 2012-03-01
3: 2012-05-12
Sorted by the output format dd-mm-yyyy it will look like this...
1: 01-03-2012
2: 03-01-2012
3: 12-05-2012
...and I doubt this is what most people want.
Adjusting the output via SQL
You can change the output in your SELECT-query , most RDBMS offer functions for this. For example, in MySQL it is DATE_FORMAT, which looks like this:
SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');
Adjusting the output via SQL
You can also change the output using php, which is explained here.
Adjusting the output via JavaScript
It isn't hard to do this in JavaScript, too: Here is a great SO post which explains it in detail.
Ok so I have a mysql database and I need an updated_at field and a created_at field like ruby on rails has by default. I was thinking of using a timestamp for the updated field and a datetime for a created at field. I was reading this article to help me choose but i still dont know if there is a standard that is followed that will either do this automatically with automatically or with little extra code...any ideas on this
The best practice would be to use UNIX Timestamps on both.
To have UNIX timestamp in PHP, use the
time();
function, and to have it in MySQL use the
UNIX_TIMESTAMP();
function. PHP can simply convert UNIX timestamps to any formatted date string using
Date();
function. And you can also make calculations with that.
Well the code from php will only provide you with your time as your computer see's it. Where mysql it has the CURRENT_TIMESTAMP.
You could do it entirely in your database management system. For example, MySQL has functions to use the current date or time: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Example: insert into a (CURRENT_TIMESTAMP);
You are on track with using TIMESTAMP for your updated field which provides the functionality you are looking for. To keep your date format consistent, I would then use DATETIME for your created field and use now() on insert.
I prefer UNIX timestamps, but then you have to code for the updated_at field.
I have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.
I have a mysql table field set as time type which stores data in the HH:mm:ss format. So when I list the data, it prints as, for example, 16:30:00. But I want to display hh:mm part only (not the seconds).
In case of datetime types, I can do date('H:i', '2010-03-16 16:30:00'). I mean I can retrieve any part. I wonder if there is any similar way like this for time only fields??
Please see, I can manipulate the time string to get rid of seconds in time part using str_replace, explode etc, I just wonder if there is any standard function there which I am not aware of.
If you want to do this with PHP, you'd have to get a timestamp from the time first, e.g.
echo date('H:i', strtotime('16:30:00'));
will output 16:30. Strtotime will assume the time is for the current date then.
You can let MySQL return the data in the format you want using Date_Format()
edit: as fireeyedboy pointed out there's also a TIME_FORMAT() function.
Another approach is:
SELECT UNIX_TIMESTAMP(time_field) AS tstamp FROM table;
Then you can use PHP's date() function to format it.
$time = date('H:i', $tstamp);