SQLite3で日時のフォーマットを指定するサンプル

環境
Windows 11 Pro 21H2 64bit
SQLite 3.39.2

構文
strftime('フォーマット形式’,日付)
strftime関数を使って、日時のフォーマットを指定します。

フォーマット形式
%Y 年
%m 月
%d 日
%W 年始めからの週数
%j 年始めからの経過日数
%w 曜日: (日曜日 0)
%H 時
%M 分
%S 秒

使用例
1.データベースを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
C:\study\sqlite>sqlite3 test.sqlite3
SQLite version 3.39.2 2022-07-21 15:24:47
Enter ".help" for usage hints.
sqlite>
C:\study\sqlite>sqlite3 test.sqlite3 SQLite version 3.39.2 2022-07-21 15:24:47 Enter ".help" for usage hints. sqlite>
C:\study\sqlite>sqlite3 test.sqlite3
SQLite version 3.39.2 2022-07-21 15:24:47
Enter ".help" for usage hints.
sqlite>

2.テーブルを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> create table usertbl(uid,uname,regdate);
sqlite> create table usertbl(uid,uname,regdate);
sqlite> create table usertbl(uid,uname,regdate);

3.データを挿入します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> insert into usertbl values('1001','user001',current_timestamp);
sqlite> insert into usertbl values('1001','user001',current_timestamp);
sqlite> insert into usertbl values('1001','user001',current_timestamp);

 

4.列名「regdate」の「年月日」形式に変換して取得します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> select regdate,strftime('%Y年%m月%d日', regdate) from usertbl;
sqlite> select regdate,strftime('%Y年%m月%d日', regdate) from usertbl;
sqlite> select regdate,strftime('%Y年%m月%d日', regdate) from usertbl;

実行結果
2022-09-12 21:37:09|2022年09月12日

5.列名「regdate」の「時分秒」形式に変換して取得します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> select regdate,strftime('%Y年%m月%d日 %H時%M分%S秒', regdate) from usertbl;
sqlite> select regdate,strftime('%Y年%m月%d日 %H時%M分%S秒', regdate) from usertbl;
sqlite> select regdate,strftime('%Y年%m月%d日 %H時%M分%S秒', regdate) from usertbl;

実行結果
2022-09-12 21:37:09|2022年09月12日 21時37分09秒

SQLite

Posted by arkgame