LoginSignup
4

More than 5 years have passed since last update.

Titanium mobileのString.formatを使ってみる

Posted at

Titanium mobile "early" Advent Calendar 2012-24日目

日付などを表示するのに

foo.js
y + ''  + m + '' + d + ''  

などとしていませんか?。
もちろんそれでも問題なく動作しますが日本語以外にも対応したい場合はどうでしょう。
そんな時にTitaniumが用意してくれているStringメソッドを使えばいい感じに表示をしてくれます。
例えば日付を表すためのformatDate(date, format)とformatTime(date, format)は

foo.js
  date = new Date();
  String.formatDate(date, "long");//iOSのみ
  String.formatDate(date, "medium");
  String.formatDate(date, "short");
  String.formatTime(date, "long");//iOSのみ
  String.formatTime(date, "medium");
  String.formatTime(date, "short");

これらは日本語だと

foo.js
  //=> 2012年11月23日
  //=> 2012/11/23
  //=> 2012/11/23
  //=> 21:44:21 JST
  //=> 21:44:21
  //=> 21:44

端末の言語が英語環境だと

foo.js
  //=> November 23, 2012
  //=> Nov 23, 2012
  //=> 11/23/12
  //=> 9:58:31 PM GMT+09:00
  //=> 9:58:31 PM
  //=> 9:58 PM

フランス語だと

foo.js
  //=> 23 novembre 2012
  //=> 23 nov. 2012
  //=> 23/11/12
  //=> 22:50:09 UTC+09:00
  //=> 22:50:09
  //=> 22:50

などに切り替えてくれます。

また通貨だとformatCurrency (value)を使い

foo.js
  Ti.API.info(String.formatCurrency(1500));
  //=> $1,500.00  (英語環境)
  //=> ¥1,500    (日本語環境)
  //=> 1 500,00 € (フランス語環境)

と切替ることができます。

また数字の桁あわせをしたい場合はformatDecimall (value, locale, pattern)で

foo.js
  Ti.API.info(String.formatDecimal(15.678, "en-US", "#"));
  //=> 16
  Ti.API.info(String.formatDecimal(15.678, "en-US", "#.##"));
  //=> 15.68
  Ti.API.info(String.formatDecimal(15, "en-US", "0000"));
  //=> 0015
  Ti.API.info(String.formatDecimal(1500, "en-US", "#,###"));
  //=> 1,500

とします。

さらにString.format (formatString, value)はC言語などのprintf型式でフォーマットの型を指定できるので柔軟なフォーマットが可能です。
ただ、iOSではバグがあって、

foo.js
  Ti.API.info(String.format("%4d-%2d-%2d %2d:%2d", 2011, 1, 1, 23, 5));
  //=> 2011-01-01 23:05(こう表示されることを期待するのだが)
  //=> 0-1084189696- 0 1072693248: 0(iOSではうまく動作せず)

とおかしな表示になってしまいます。
そこで不恰好ですが

foo.js
  Ti.API.info(String.format("%04.0f-%02.0f-%02.0f %02.0f:%02.0f", 2011, 1, 1, 23, 5));
  //=> 2011-01-01 23:05

とすると期待通りに表示できました。

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
4