3
3

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 5 years have passed since last update.

JAVA SimpleDateFormat

Last updated at Posted at 2015-11-11

独自に書式を指定して「2015年11月11日16時」の様な文字列を生成したい場合は、java.text.SimpleDateFormatクラスを使います。

■DateからStringを生成する
Date now = new Date();
SimpleDateFormat f = new SimpleDateFormat(書式文字列);
String s = f.format(now);

■StringからDateを生成する
SimpleDateFormat f = new SimpleDateFormat(書式文字列);
Date nnn = f.parse(文字列);


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test03 {
	public static void main(String[] args) throws ParseException {
		Date now = new Date();
		SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String s = f.format(now);
		System.out.println(s);

		SimpleDateFormat aa = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒");
		String bb = aa.format(now);
		System.out.println(bb);

		Date nnn = f.parse("2007/05/21 16:20:26");
		System.out.println(nnn);

		SimpleDateFormat xx = new SimpleDateFormat("MM月dd日");
		String yy = xx.format(now);
		System.out.println(yy);
	}

}

実行結果
2015/11/11 16:42:10
2015年11月11日 16時42分10秒
Mon May 21 16:20:26 JST 2007
11月11日

詳しく__________________________

StringからDateを生成する
		Date nnn = f.parse("2007/05/21 16:20:26");
		System.out.println(nnn);

StringからDateを生成する 実行結果
Mon May 21 16:20:26 JST 2007
DateからStringを生成する
		Date now = new Date();
		SimpleDateFormat xx = new SimpleDateFormat("MM月dd日");
		String yy = xx.format(now);
		System.out.println(yy);

DateからStringを生成する 実行結果
11月11日

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test03 {
	public static void main(String[] args) {
		Date now = new Date();
		SimpleDateFormat v = new SimpleDateFormat("西暦yyyy年MM月dd日");
		String y = v.format(now);
		System.out.println(y);
	}
}
実行結果
西暦2015年11月12日
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?