Java tutorial
//package com.java2s; /* * Copyright (C) 2011,2012 Southern Storm Software, Pty Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; public class Main { private static TimeZone cachedTimeZone = null; private static int cachedOffset = 0; /** * Parses a date/time string from within an XMLTV stream. Only the local * time part of the value is parsed. Timezone specifications are ignored. * * @param str the string * @param convertTimezone true to convert date/time values to local time * @return the date/time value as a Calendar object */ public static Calendar parseDateTime(String str, boolean convertTimezone) { // Format looks like: 20111209060000 +1100 if (str == null) return null; int year = parseField(str, 0, 4); int month = parseField(str, 4, 2); int day = parseField(str, 6, 2); int hour = parseField(str, 8, 2); int minute = parseField(str, 10, 2); int second = parseField(str, 12, 2); if (convertTimezone) { if (cachedTimeZone == null) { cachedTimeZone = TimeZone.getDefault(); cachedOffset = cachedTimeZone.getOffset(System.currentTimeMillis()); } int tz = parseTZField(str, 14); if (tz != cachedOffset) { Calendar calendar = new GregorianCalendar(year, month - 1, day, hour, minute, second); calendar.add(Calendar.MILLISECOND, cachedOffset - tz); return calendar; } } return new GregorianCalendar(year, month - 1, day, hour, minute, second); } /** * Parses a fixed-length numeric field out of a string. * * @param str the string * @param posn the starting position within the string * @param length the length of the field * @return the numeric value */ public static int parseField(String str, int posn, int length) { int value = 0; while (length-- > 0) { if (posn >= str.length()) break; char ch = str.charAt(posn++); if (ch >= '0' && ch <= '9') value = value * 10 + ch - '0'; } return value; } private static int parseTZField(String str, int posn) { while (posn < str.length() && str.charAt(posn) == ' ') { ++posn; } if (posn >= str.length()) return cachedOffset; boolean positive; if (str.charAt(posn) == '+') { positive = true; ++posn; } else if (str.charAt(posn) == '-') { positive = false; ++posn; } else { return cachedOffset; } int raw = parseField(str, posn, 4); int value = ((raw / 100) * 60 + (raw % 100)) * (60 * 1000); if (positive) return value; else return -value; } }