Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you format 24-hour time string into 12-hour time string with AM/PM?

Tags:

sqlite

I store some time values in sqlite in %H:%M string format (for example "15:43"), but I would like to get them out formatted in 12 hour format with AM/PM indicators (for example "3:43 PM"). Is this possible with sqlite (and if so, how), or do I need to do this in my application code?

like image 668
Heikki Toivonen Avatar asked Feb 11 '09 08:02

Heikki Toivonen


4 Answers

Unless you extend sqlite with your own custom function, you'll have to do this is code.

sqlite's strftime date formatting function only supports a small subset of its C counterpart, insufficient for your problem. sqlite also lacks a selection construct like IF or CASE, making simple if/else impossible.

like image 167
Paul Dixon Avatar answered Sep 23 '22 02:09

Paul Dixon


Some pseudo code to help you on the way:

if (hourpart of time >= 12)
    subtract 12 from hours
    append string " pm"
else // hourpart < 12
    append string " am"
end if

In SQL you can accomplish this using the CASE syntax.


After taking a closer look at the problem:

SELECT (CASE HOUR(myTimeColumn) >= 12 WHEN 1 THEN
         ((HOUR(myTimeColumn) - 12) + '-' + MINUTE(myTimeColumn) + ' pm')
       ELSE
         (HOUR(myTimeColumn) + '-' + MINUTE(myTimeColumn) + ' am')
       AS AmPmTime,
       someOtherColumn
FROM myTable

I'm not entirely sure that all of that is valid SQLite syntax, but you should be able to correct the bugs.

like image 44
Tomas Aschan Avatar answered Sep 23 '22 02:09

Tomas Aschan


There are a few special situation that are covered here. I'm using 'now' as a source, but you can adjust it for your string:

select
  CASE 
  --For 00:05, for example.
  WHEN (strftime('%H', 'now', 'localtime') - 12) = -12
  THEN  '12:' || strftime('%M', 'now', 'localtime') ||' '|| 'AM'
  --For 12:05, for example.
  WHEN (strftime('%H', 'now', 'localtime') - 12) = 0
  THEN '12:' || strftime('%M', 'now', 'localtime') ||' '|| 'PM'
  --other am time
  WHEN (strftime('%H', 'now', 'localtime') - 12) < 0
  THEN  strftime('%H', 'now', 'localtime') ||':'||
    strftime('%M', 'now', 'localtime') ||' '|| 'AM'
  ELSE
  --other pm time
    (cast(strftime('%H', 'now', 'localtime') as integer) - 12) ||':'||
    strftime('%M', 'now', 'localtime') ||' '|| 'PM'
  END here_you_go_usa;
like image 40
Taurus16 Avatar answered Sep 21 '22 02:09

Taurus16


Do it in your application. Store it in normal 24h format in the database. In the database it can be stored as a Date entry instead of a string (correct me if im wrong)

like image 41
RvdK Avatar answered Sep 25 '22 02:09

RvdK