Skip to content

Instantly share code, notes, and snippets.

@ochim
Created May 17, 2016 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochim/89f474d197ca8d1429f384b9f3d0195b to your computer and use it in GitHub Desktop.
Save ochim/89f474d197ca8d1429f384b9f3d0195b to your computer and use it in GitHub Desktop.
[Android] 現在日時の取得方法

概要

端末の現在日時を「yyyy/MM/dd HH:mm:ss」形式の文字列で取得する。

サンプルコード

/**
 * 現在日時をyyyy/MM/dd HH:mm:ss形式で取得する.<br>
 */
public static String getNowDate(){
    final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    final Date date = new Date(System.currentTimeMillis());
    return df.format(date);
}

ポイント

  1. SimpleDateFormatのコンストラクタの引数で取得する日時形式を決定している。
  2. System.currentTimeMillis()で端末時刻を通算ミリ秒で取得し、Dataのコンストラクタの引数に渡すことで現在時刻のDataインスタンスを取得している。
  3. DataFormat#format()に現在時刻のDataインスタンスを引数として渡し、現在日時を指定した形式で取得している。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment