ログを読んで日付行からカレンダーをオブジェクトをつくる
2008/06/17
java
正規表現
Javaです。
たとえば、2008-02-29 00:22:01,177とかなんとかのログ行を読んでカレンダーオブジェクトをつくってみます。
正規表現でマッチさせて、Calendarにセットしていきます。
package l;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestA {
static int toint(String s) {
// System.out.println(s);
return Integer.parseInt(s);
}
public static void main(String[] args) {
aa("2008-01-01 23:22:01,484");
aa("2008-02-01 08:22:01,921");
aa("2008-02-29 00:22:01,177");
aa("2008-03-01 00:22:01,003");
}
static void aa(String s) {
Pattern pattern = Pattern
.compile("^(\\d{2,4})-(\\d{1,2})-(\\d{1,2}) (\\d{1,2})\\:(\\d{1,2})\\:(\\d{1,2}),(\\d{1,3}).*");
System.out.println();
Matcher matcher = pattern.matcher(s);
Calendar calendar = Calendar.getInstance();
if (matcher.find()) {
int pos = 0;
System.err.println(matcher.group(pos++));
calendar.set(Calendar.YEAR, toint(matcher.group(pos++)));
calendar.set(Calendar.MONTH, toint(matcher.group(pos++)) - 1);
calendar.set(Calendar.DAY_OF_MONTH, toint(matcher.group(pos++)));
calendar.set(Calendar.HOUR_OF_DAY, toint(matcher.group(pos++)));
calendar.set(Calendar.MINUTE, toint(matcher.group(pos++)));
calendar.set(Calendar.SECOND, toint(matcher.group(pos++)));
calendar.set(Calendar.MILLISECOND, toint(matcher.group(pos++)));
}
System.out.println(calendar);
System.out.println(calendar.getTime().toGMTString());
System.out.println(calendar.getTime().toLocaleString());
}
}
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestA {
static int toint(String s) {
// System.out.println(s);
return Integer.parseInt(s);
}
public static void main(String[] args) {
aa("2008-01-01 23:22:01,484");
aa("2008-02-01 08:22:01,921");
aa("2008-02-29 00:22:01,177");
aa("2008-03-01 00:22:01,003");
}
static void aa(String s) {
Pattern pattern = Pattern
.compile("^(\\d{2,4})-(\\d{1,2})-(\\d{1,2}) (\\d{1,2})\\:(\\d{1,2})\\:(\\d{1,2}),(\\d{1,3}).*");
System.out.println();
Matcher matcher = pattern.matcher(s);
Calendar calendar = Calendar.getInstance();
if (matcher.find()) {
int pos = 0;
System.err.println(matcher.group(pos++));
calendar.set(Calendar.YEAR, toint(matcher.group(pos++)));
calendar.set(Calendar.MONTH, toint(matcher.group(pos++)) - 1);
calendar.set(Calendar.DAY_OF_MONTH, toint(matcher.group(pos++)));
calendar.set(Calendar.HOUR_OF_DAY, toint(matcher.group(pos++)));
calendar.set(Calendar.MINUTE, toint(matcher.group(pos++)));
calendar.set(Calendar.SECOND, toint(matcher.group(pos++)));
calendar.set(Calendar.MILLISECOND, toint(matcher.group(pos++)));
}
System.out.println(calendar);
System.out.println(calendar.getTime().toGMTString());
System.out.println(calendar.getTime().toLocaleString());
}
}
: