4
4

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 文字列が正しい日時を表しているかの判定

Last updated at Posted at 2016-02-03

はじめに

事前に準備する外部ライブラリ等はありません。
JavaSEに含まれるjava.text.SimpleDateFormatクラスを使用します。

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。

DateChecker.java
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 *
 * @author tool-taro.com
 */
public class DateChecker {

	public static void main(String[] args) {

		//判定したい文字列
		String source = "2016/02/02 12:34:56";
		//判定したいパターン
		String pattern = "yyyy/MM/dd HH:mm:ss";

		//判定処理
		boolean result = false;
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(pattern);
			//存在しない日(例 2017/02/29)の場合はfalseとする
			result = source.equals(formatter.format(formatter.parse(source)));
		}
		catch (ParseException e) {
		}
		//標準出力
		System.out.format("判定結果=%1$b", result);
	}
}

動作確認

$ javac DateChecker.java
$ java DateChecker
$ 判定結果=true

環境

  • 開発

    • Windows 10 Pro
    • JDK 1.8.0_112
    • NetBeans IDE 8.2
  • 動作検証

    • CentOS Linux release 7.2
    • JDK 1.8.0_112

Webツールも公開しています。
Web便利ツール@ツールタロウ

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?