0
0

Spring 掲示板機能で、投稿時に作成日を表示させる方法 備忘録#1

Last updated at Posted at 2024-06-04

Spring 掲示板機能で、投稿時に作成日を表示させる方法

実行しようとした昨日

今回以下のように作成日を、投稿と同時に自動的に付けてくれる機能を実装しようとしました。
無事作成できたので、備忘録として投稿しようと思います。

スクリーンショット 2024-06-03 22.54.30.png

データベース設計

schema.sql
-- テーブル削除
DROP TABLE IF EXISTS posts;

-- カテゴリーテーブル
CREATE TABLE  posts
(
   id SERIAL PRIMARY KEY,
   title TEXT,
   content TEXT,
   create_date DATE,
   comments TEXT
);

Entity

Enitityでは、作成日をcreateDateとして扱います。

Post.java
package com.example.demo.entity;

@Entity
@Table(name = "posts")
public class Post {
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String title;
    private String content;
    @Column(name = "create_date")
    private LocalDate createDate;
    private String comments;
    
    public Post() {
        
    }
    
    public Post(String comments) {
        this.comments = comments;
    }
    
    public Post(String title, String content) {
        this.title = title;
        this.content = content;
        //コンストラクタの引数には入れず、フィールドに入れることで、作成時に現在の日付を表示。
        this.createDate = LocalDate.now();
    }
    
    public Post(Integer id,String title, String content, String comments){
        this.id = id;
        this.comments = comments;
        this.title = title;
        this.content = content;
    }
    
    public Post(String title, String content, String comments){
        this.comments = comments;
        this.title = title;
        this.content = content;
    }
    //ゲッター、セッター省略
}

HTML

タイムタイムリーフで、フォーマットを指定することができる。

post.html
 <table border="1" class="table">
        <tr class="table-secondary">
          <th>タイトル</th>
          <th>内容</th>
          <th>作成日</th>
        </tr>
        <tr th:each="post:${posts}">
          <td><a th:href="@{/detail/{postId}/show(postId=${post.id})}" th:text="${post.title}"></a></td>
          <td><a th:href="@{/detail/{postId}/show(postId=${post.id})}" th:text="${post.content}"></a></td>

          //以下のように書くことで、フォーマットを指定する。
          //出力結果:「06/04」
           <td th:text="${#temporals.format(post.createDate, 'MM/dd')}"></td>
       </tr>
      </table>

以上のようにして、投稿作成時に、作成日を自動生成することができるようになる。

これ以外にも、フォーマットの書き方として、

1 2
${#temporals.format(time, 'yyyy/MM/dd HH:mm :ss')} 日付を自由にフォーマット
${#temporals.year(date)} 年を取得
${#temporals.month(date)} 月を取得
${#temporals.day(date)} 日を取得
${#temporals.dayOfWeekName(date)} 曜日を取得
${#temporals.hour(time)} 時間を取得
${#temporals.minute(time)} 分を取得
${#temporals.second(time)} 秒を取得

があるみたいです。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0