📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

 
(同じ利用者による、間の1版が非表示)
53行目: 53行目:
ISO 8601は国際標準化機構(ISO)により定められた日付と時刻の表記に関する国際規格であり、主にデータ交換の文脈で利用される。<br>
ISO 8601は国際標準化機構(ISO)により定められた日付と時刻の表記に関する国際規格であり、主にデータ交換の文脈で利用される。<br>
<br>
<br>
==== UTC時間を日本時間に変換 ====
以下の例では、"2024-03-01T16:24:32Z"というUTCの日時 (文字列) を日本時間に変換して、"yyyy年M月d日 H時m分"という形式に変換している。<br>
以下の例では、"2024-03-01T16:24:32Z"というUTCの日時 (文字列) を日本時間に変換して、"yyyy年M月d日 H時m分"という形式に変換している。<br>
  <syntaxhighlight lang="c++">
  <syntaxhighlight lang="c++">
79行目: 80行目:
  std::cout << formattedDateTime.toStdString() << std::endl;
  std::cout << formattedDateTime.toStdString() << std::endl;
  }
  }
</syntaxhighlight>
<br>
==== 文字列を日時に変換 ====
まず、<code>QDateTime::fromString</code>メソッドを使用して文字列を<code>QDateTime</code>クラスのオブジェクトに変換する。<br>
次に、<code>QDateTime::toString</code>メソッドを使用して任意の形式 (カスタムの日付フォーマットも指定可能) に変換する。<br>
<syntaxhighlight lang="c++">
#include <QDateTime>
// ISO 8601形式の日本時間
QString isoDateStr = "2024-03-02T17:17:00+09:00";
QDateTime dateTime = QDateTime::fromString(isoDateStr, Qt::ISODate);
if (!dateTime.isValid()) {
    std::cerr << QString("日付の変換に失敗しました").toStdString() << std::endl;
    return -1;
}
// "yyyy年M月d日 H時m分"形式に変換
// 時間の表記を"M月d日"や"H時m分"とすることにより、0を付加しない日時に変換できる
QString formattedDateStr = dateTime.toString("yyyy年M月d日 H時m分");
std::cout << QString("変換後の日付と時間 : %1").arg(formattedDateStr).toStdString() << std::endl;
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>
189行目: 212行目:
  else if (now < compareDate) qDebug() << "指定の日時より前です";
  else if (now < compareDate) qDebug() << "指定の日時より前です";
  else                        qDebug() << "指定の日時と同じです";
  else                        qDebug() << "指定の日時と同じです";
</syntaxhighlight>
<br>
以下の例では、現在の日本時間と比較して2日以内かどうかを確認している。<br>
<syntaxhighlight lang="c++">
#include <QDateTime>
QString dateString = "2024年3月31日 12時35分";
QDateTime date = QDateTime::fromString(dateString, "yyyy年M月d日 h時m分");
QDateTime nowDate = QDateTime::currentDateTime();
nowDate.setTimeZone(QTimeZone("Asia/Tokyo"));
// 現在の日付から2日以内かどうかを確認
if (date.daysTo(nowDate) <= 2) {
    std::cout << QString("2日以内です").toStdString() << std::endl;
}
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>