見出し画像

DelphiでWinRT DateTimeFormatterクラスを使う

Delphi 10.3WinRTDateTimeFormatterを利用する場合、Winapi.Globalizationをusesに追加する必要があります。最新のDelphiではWinRT対応されており、DateTimeFormatterクラスを使う場合TDateTimeFormatting_DateTimeFormatterを使います。これはDelphiのクラスです。このクラスのインスタンス作成するには、CreateDateTimeFormatter()を使います。其の場合、引数にフォーマット用の文字列を入れるのですが、そこはDelphiのString(文字列)ではなくHSTRINGである必要があります。DelphiにはStringからHSTRINGへ変換が用意されています。HSTRING変換にはDelphiのTWindowsStringというrecordが用意されていますので、この2つを組み合わせることで下記コードのようにDateTimeFormatterが利用できるようになります。

procedure TForm1.Button1Click(Sender: TObject);
var
  s1: TWindowsString;
begin
  s1  := TWindowsString.Create('{year.full}/{month.integer(2)}/{day.integer(2)} {hour.integer(2)}:{minute.integer(2)} ({timezone.full})');
  var dtFmt := TDateTimeFormatting_DateTimeFormatter.CreateDateTimeFormatter(s1);
end;

WinRTの日時フォーマットは{year.full}{month.full}のような書き方になります。CreateDateTimeFormatter()を実行した変数はDateTimeFormatting_IDateTimeFormatter型と云うインターフェイスで作られます。なので、上記コードの場合、var dtFmt:DateTimeFormatting_IDateTimeFormatterです。

画像1

DateTimeFormatting_IDateTimeFormatterインターフェイスには、function Format(value: DateTime): HSTRING; safecall;メソッドがいます。そこに以前怪獣農場で説明したTDateTimeからWinRT DateTimeに変換してFormat()引数に設定するとHSTRINGで返ります。

var s:HSTRING := dtFmt.Format(TDateTimeToDateTime(Now));

s:HSTRINGが確認できないのでDelphiのStringへ変換してみます。TWindowsStringレコードは内部にclass function HStringToString(const hs: HSTRING): string; static;を持っていますので1行でDelphiの文字列に変換できます。s:HSTRINGの結果をOutputDebugString()に出力するには下記のようなコードで可能です。

OutputDebugString( PChar(TWindowsString.HStringToString(s)));

Format()が失敗した場合「EOleException (メッセージ 'パラメーターが間違っています。')」が表示されます。WinRTが使われている感じがします。

RoInitializeはいつ発動しているのだろうか

この記事が気に入ったらサポートをしてみませんか?