Skip to content

Instantly share code, notes, and snippets.

@ucchyocean
Created February 25, 2014 17:27
Show Gist options
  • Save ucchyocean/9213643 to your computer and use it in GitHub Desktop.
Save ucchyocean/9213643 to your computer and use it in GitHub Desktop.
SimpleDateFormatを使ったパースのサンプル
public static void main(String[] args) {
String[] testees = {"23:59:59", "03:02", "1:01:01"};
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
for ( String t : testees ) {
if ( t.split(":").length < 3 ) {
t = "0:" + t; // 無理やりの回避策
}
try {
Date date = format.parse(t);
cal.setTime(date);
System.out.println(String.format("時=%d, 分=%d, 秒=%d",
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));
} catch (ParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
@ucchyocean
Copy link
Author

↑の実行結果。


時=23, 分=59, 秒=59
時=0, 分=3, 秒=2
時=1, 分=1, 秒=1


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment