0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftでDate型をユーザーに合わせてフォーマットする方法 強制的に西暦にする、など

Last updated at Posted at 2023-05-20

宣伝

アプリ作っているので入れてみてください!!
よろしくお願いいたします!!

本題

以下の関数をコピペで使えます。

// 関数: formatDateToString
// Date型をStringにフォーマットする関数

func formatDateToString(date: Date) -> String {
    // DateFormatterインスタンスを作成
    let dateFormatter = DateFormatter()
    
    // dateStyleを.mediumに設定し、日付を表示する形式を指定
    dateFormatter.dateStyle = .medium
    
    // timeStyleを.noneに設定し、時間を表示しないように指定
    dateFormatter.timeStyle = .none
    
    // DateFormatterを使ってDate型をStringに変換
    let formattedString = dateFormatter.string(from: date)
    
    // 変換されたStringを返す
    return formattedString
}

dateStyleとtimeStyleには以下の値を設定することができます。

dateStyleの値:

.none: 日付を表示しない
.short: 短い形式の日付を表示 (例: 2022/01/01)
.medium: 中間の形式の日付を表示 (例: Jan 1, 2022)
.long: 長い形式の日付を表示 (例: January 1, 2022)
.full: 完全な形式の日付を表示 (例: Saturday, January 1, 2022)
timeStyleの値:

.none: 時間を表示しない
.short: 短い形式の時間を表示 (例: 13:30)
.medium: 中間の形式の時間を表示 (例: 13:30:00)
.long: 長い形式の時間を表示 (例: 13:30:00 GMT+09:00)
.full: 完全な形式の時間を表示 (例: 13:30:00 JST)

これらの値を組み合わせることで、さまざまな日付と時間の表示形式を選択することができます。適切な形式を選ぶためには、ユーザーのニーズやアプリのコンテキストに合わせて選択することが重要です。

これを使うことで、例えば令和表記にしているユーザには令和で表示されることになり、世界のいろいろな時間の表記法にも勝手に変換してくれるようです。

年号だけは指定のに指定場合は以下のように設定できます。

// 関数: formatDateToString
// Date型をStringにフォーマットする関数

func formatDateToString(date: Date) -> String {
    // DateFormatterインスタンスを作成
    let dateFormatter = DateFormatter()
    
    // カレンダーをグレゴリオ暦に設定
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    
    // dateStyleを.mediumに設定し、日付を表示する形式を指定
    dateFormatter.dateStyle = .medium
    
    // timeStyleを.noneに設定し、時間を表示しないように指定
    dateFormatter.timeStyle = .none
    
    // DateFormatterを使ってDate型をStringに変換
    let formattedString = dateFormatter.string(from: date)
    
    // 変換されたStringを返す
    return formattedString
}


Calendar(identifier: .gregorian)によってカレンダーをグレゴリオ暦に設定していますが、Calendarクラスのidentifierプロパティには他にもさまざまな値を指定することができます。いくつか一般的な値を挙げると、次のようなものがあります:

.gregorian: グレゴリオ暦
.buddhist: 仏暦
.chinese: 中国暦
.hebrew: ヘブライ暦
.islamic: イスラム暦
.japanese: 和暦
.persian: ペルシャ暦
.republicOfChina: 中華民国暦(台湾暦)
これらの値をCalendar(identifier:)に指定することで、異なるカレンダーシステムを使用することができます。ただし、使用可能なカレンダーはプラットフォームや地域によって異なる場合があります。

作ったアプリ。

では。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?