Java/Data Type/Date Parser
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
Date parser for ISO 8601 format
// DateParser.java
// $Id: DateParser.java,v 1.5 2005/05/16 10:19:19 ylafon Exp $
// (c) COPYRIGHT MIT, INRIA and Keio, 2000.
// Please first read the full copyright statement in file COPYRIGHT.html
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TimeZone;
/**
* Date parser for ISO 8601 format
* http://www.w3.org/TR/1998/NOTE-datetime-19980827
*
* @version $Revision: 1.5 $
* @author Benoît Mahé (bmahe@w3.org)
* @author Yves Lafon (ylafon@w3.org)
*/
public class DateParser {
private static boolean check(StringTokenizer st, String token)
{
try {
if (st.nextToken().equals(token)) {
return true;
} else {
throw new RuntimeException("Missing [" + token + "]");
}
} catch (NoSuchElementException ex) {
return false;
}
}
private static Calendar getCalendar(String isodate) {
// YYYY-MM-DDThh:mm:ss.sTZD
StringTokenizer st = new StringTokenizer(isodate, "-T:.+Z", true);
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.clear();
try {
// Year
if (st.hasMoreTokens()) {
int year = Integer.parseInt(st.nextToken());
calendar.set(Calendar.YEAR, year);
} else {
return calendar;
}
// Month
if (check(st, "-") && (st.hasMoreTokens())) {
int month = Integer.parseInt(st.nextToken()) - 1;
calendar.set(Calendar.MONTH, month);
} else {
return calendar;
}
// Day
if (check(st, "-") && (st.hasMoreTokens())) {
int day = Integer.parseInt(st.nextToken());
calendar.set(Calendar.DAY_OF_MONTH, day);
} else {
return calendar;
}
// Hour
if (check(st, "T") && (st.hasMoreTokens())) {
int hour = Integer.parseInt(st.nextToken());
calendar.set(Calendar.HOUR_OF_DAY, hour);
} else {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
// Minutes
if (check(st, ":") && (st.hasMoreTokens())) {
int minutes = Integer.parseInt(st.nextToken());
calendar.set(Calendar.MINUTE, minutes);
} else {
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
//
// Not mandatory now
//
// Secondes
if (!st.hasMoreTokens()) {
return calendar;
}
String tok = st.nextToken();
if (tok.equals(":")) { // secondes
if (st.hasMoreTokens()) {
int secondes = Integer.parseInt(st.nextToken());
calendar.set(Calendar.SECOND, secondes);
if (!st.hasMoreTokens()) {
return calendar;
}
// frac sec
tok = st.nextToken();
if (tok.equals(".")) {
// bug fixed, thx to Martin Bottcher
String nt = st.nextToken();
while (nt.length() < 3) {
nt += "0";
}
nt = nt.substring(0, 3); // Cut trailing chars..
int millisec = Integer.parseInt(nt);
// int millisec = Integer.parseInt(st.nextToken()) * 10;
calendar.set(Calendar.MILLISECOND, millisec);
if (!st.hasMoreTokens()) {
return calendar;
}
tok = st.nextToken();
} else {
calendar.set(Calendar.MILLISECOND, 0);
}
} else {
throw new RuntimeException("No secondes specified");
}
} else {
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
// Timezone
if (!tok.equals("Z")) { // UTC
if (!(tok.equals("+") || tok.equals("-"))) {
throw new RuntimeException("only Z, + or - allowed");
}
boolean plus = tok.equals("+");
if (!st.hasMoreTokens()) {
throw new RuntimeException("Missing hour field");
}
int tzhour = Integer.parseInt(st.nextToken());
int tzmin = 0;
if (check(st, ":") && (st.hasMoreTokens())) {
tzmin = Integer.parseInt(st.nextToken());
} else {
throw new RuntimeException("Missing minute field");
}
if (plus) {
calendar.add(Calendar.HOUR, -tzhour);
calendar.add(Calendar.MINUTE, -tzmin);
} else {
calendar.add(Calendar.HOUR, tzhour);
calendar.add(Calendar.MINUTE, tzmin);
}
}
} catch (NumberFormatException ex) {
throw new RuntimeException("[" + ex.getMessage() + "] is not an integer");
}
return calendar;
}
/**
* Parse the given string in ISO 8601 format and build a Date object.
*
* @param isodate
* the date in ISO 8601 format
* @return a Date instance
* @exception InvalidDateException
* if the date is not valid
*/
public static Date parse(String isodate) {
Calendar calendar = getCalendar(isodate);
return calendar.getTime();
}
private static String twoDigit(int i) {
if (i >= 0 && i < 10) {
return "0" + String.valueOf(i);
}
return String.valueOf(i);
}
/**
* Generate a ISO 8601 date
*
* @param date
* a Date instance
* @return a string representing the date in the ISO 8601 format
*/
public static String getIsoDate(Date date) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
StringBuffer buffer = new StringBuffer();
buffer.append(calendar.get(Calendar.YEAR));
buffer.append("-");
buffer.append(twoDigit(calendar.get(Calendar.MONTH) + 1));
buffer.append("-");
buffer.append(twoDigit(calendar.get(Calendar.DAY_OF_MONTH)));
buffer.append("T");
buffer.append(twoDigit(calendar.get(Calendar.HOUR_OF_DAY)));
buffer.append(":");
buffer.append(twoDigit(calendar.get(Calendar.MINUTE)));
buffer.append(":");
buffer.append(twoDigit(calendar.get(Calendar.SECOND)));
buffer.append(".");
buffer.append(twoDigit(calendar.get(Calendar.MILLISECOND) / 10));
buffer.append("Z");
return buffer.toString();
}
/**
* Generate a ISO 8601 date
*
* @param date
* a Date instance
* @return a string representing the date in the ISO 8601 format
*/
public static String getIsoDateNoMillis(Date date) {
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.setTime(date);
StringBuffer buffer = new StringBuffer();
buffer.append(calendar.get(Calendar.YEAR));
buffer.append("-");
buffer.append(twoDigit(calendar.get(Calendar.MONTH) + 1));
buffer.append("-");
buffer.append(twoDigit(calendar.get(Calendar.DAY_OF_MONTH)));
buffer.append("T");
buffer.append(twoDigit(calendar.get(Calendar.HOUR_OF_DAY)));
buffer.append(":");
buffer.append(twoDigit(calendar.get(Calendar.MINUTE)));
buffer.append(":");
buffer.append(twoDigit(calendar.get(Calendar.SECOND)));
buffer.append("Z");
return buffer.toString();
}
public static void test(String isodate) {
System.out.println("----------------------------------");
Date date = parse(isodate);
System.out.println(">> " + isodate);
System.out.println(">> " + date.toString() + " [" + date.getTime() + "]");
System.out.println(">> " + getIsoDate(date));
System.out.println("----------------------------------");
}
public static void test(Date date) {
String isodate = null;
System.out.println("----------------------------------");
System.out.println(">> " + date.toString() + " [" + date.getTime() + "]");
isodate = getIsoDate(date);
System.out.println(">> " + isodate);
date = parse(isodate);
System.out.println(">> " + date.toString() + " [" + date.getTime() + "]");
System.out.println("----------------------------------");
}
public static void main(String args[]) {
test("1997-07-16T19:20:30.45-02:00");
test("1997-07-16T19:20:30+01:00");
test("1997-07-16T19:20:30+01:00");
test("1997-07-16T12:20:30-06:00");
test("1997-07-16T19:20");
test("1997-07-16");
test("1997-07");
test("1997");
test(new Date());
}
}
Date To String
/*******************************************************************************
* Copyright 2008 Mjrz.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* @author Mjrz contact@mjrz.net
*
*/
public class DateUtils {
public static final String FORMAT_YYYYMMDD = "yyyy-MM-dd";
public static final String FORMAT_YYYYMMDD_SLASHES = "yyyy/MM/dd";
public static final String GENERIC_DISPLAY_FORMAT = "E, dd MMM yyyy";
public static final String TIME_DISPLAY_FORMAT = "HH mm ss";
public static final int LAST_WEEK = 1;
public static final int LAST_MONTH = 2;
public static final String formatDate(Date dt, String format) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dt);
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getDefault());
return (sdf.format(cal.getTime()));
}
public static final String getCurrentDate(String format) {
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getDefault());
return (sdf.format(cal.getTime()));
}
public static final String dateToString(Date dt, String dateformat) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dt);
StringBuffer ret = new StringBuffer();
String separator = new String();
if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD) ) {
separator = "-";
}
if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD_SLASHES) ) {
separator = "/";
}
ret.append(cal.get(Calendar.YEAR));
ret.append(separator);
ret.append(cal.get(Calendar.MONTH) + 1);
ret.append(separator);
ret.append(cal.get(Calendar.DATE));
return ret.toString();
}
public static final String dateToString(Date dt, String tzString, String dateformat) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dt);
cal.setTimeZone(TimeZone.getTimeZone(tzString));
StringBuffer ret = new StringBuffer();
String separator = new String();
if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD) ) {
separator = "-";
}
if(dateformat.equals(DateUtils.FORMAT_YYYYMMDD_SLASHES) ) {
separator = "/";
}
ret.append(cal.get(Calendar.YEAR));
ret.append(separator);
ret.append(cal.get(Calendar.MONTH) + 1);
ret.append(separator);
ret.append(cal.get(Calendar.DATE));
return ret.toString();
}
public static final String getTimeFromDate(Date dt) {
Calendar cal = new GregorianCalendar();
cal.setTime(dt);
StringBuffer ret = new StringBuffer();
ret.append(cal.get(Calendar.HOUR));
ret.append(":");
ret.append(cal.get(Calendar.MINUTE));
return ret.toString();
}
public static final String getTimeFromDate(Date dt, String tzString) {
try {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dt);
gc.setTimeZone(TimeZone.getTimeZone(tzString));
StringBuffer ret = new StringBuffer();
ret.append(gc.get(Calendar.HOUR));
ret.append(":");
ret.append(gc.get(Calendar.MINUTE));
ret.append(" ");
if(gc.get(Calendar.AM_PM) == 0) {
ret.append("AM");
}
else {
ret.append("PM");
}
return ret.toString();
}
catch(Exception e) {
return "";
}
}
public static final String getDateTimeFromDate(Date dt, String tzString) {
try {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dt);
gc.setTimeZone(TimeZone.getTimeZone(tzString));
StringBuffer ret = new StringBuffer();
ret.append(gc.get(Calendar.YEAR));
ret.append("-");
ret.append(gc.get(Calendar.MONTH) - 1);
ret.append("-");
ret.append(gc.get(Calendar.DATE));
ret.append(" ");
ret.append(gc.get(Calendar.HOUR));
ret.append(":");
ret.append(gc.get(Calendar.MINUTE));
ret.append(" ");
if(gc.get(Calendar.AM_PM) == 0) {
ret.append("AM");
}
else {
ret.append("PM");
}
return ret.toString();
}
catch(Exception e) {
return "";
}
}
public static final String calendarToString(Calendar cal, String dateformat) {
StringBuffer ret = new StringBuffer();
if(dateformat.equals(FORMAT_YYYYMMDD) ) {
ret.append(cal.get(Calendar.YEAR));
ret.append("-");
String month = null;
int mo = cal.get(Calendar.MONTH) + 1; /* Calendar month is zero indexed, string months are not */
if(mo < 10) {
month = "0" + mo;
}
else {
month = "" + mo;
}
ret.append(month);
ret.append("-");
String date = null;
int dt = cal.get(Calendar.DATE);
if(dt < 10) {
date = "0" + dt;
}
else {
date = "" + dt;
}
ret.append(date);
}
return ret.toString();
}
public static final GregorianCalendar getCurrentCalendar(String utimezonestring) {
try {
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeZone(TimeZone.getTimeZone(utimezonestring));
return gc;
}
catch(Exception e) {
//If exception, return server TimeStamp
return new GregorianCalendar();
}
}
public static String[] getDateRange(int cmd) {
GregorianCalendar gc = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //$NON-NLS-1$
String ret[] = new String[2];
ret[1] = sdf.format(gc.getTime());
if(cmd == LAST_WEEK) {
for(int i = 0; i < 7; i++) {
gc2.add(Calendar.DATE, -1);
}
}
if(cmd == LAST_MONTH) {
gc2.add(Calendar.MONTH, -1);
}
ret[0] = sdf.format(gc2.getTime());
return ret;
}
public static final String getDayString(int day) {
switch (day) {
case Calendar.SUNDAY:
return "SUNDAY";
case Calendar.MONDAY:
return "MONDAY";
case Calendar.TUESDAY:
return "TUESDAY";
case Calendar.WEDNESDAY:
return "WEDNESDAY";
case Calendar.THURSDAY:
return "THURSDAY";
case Calendar.FRIDAY:
return "FRIDAY";
case Calendar.SATURDAY:
return "SATURDAY";
}
return "";
}
}
ISO 8601 date parsing utility.
/*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* ISO 8601 date parsing utility. Designed for parsing the ISO subset used in
* Dublin Core, RSS 1.0, and Atom.
*
* @author
* @version $Id: ISO8601DateParser.java,v 1.2 2005/06/03 20:25:29 snoopdave Exp $
*/
public class ISO8601DateParser {
// 2004-06-14T19:GMT20:30Z
// 2004-06-20T06:GMT22:01Z
// http://www.cl.cam.ac.uk/~mgk25/iso-time.html
//
// http://www.intertwingly.net/wiki/pie/DateTime
//
// http://www.w3.org/TR/NOTE-datetime
//
// Different standards may need different levels of granularity in the date and
// time, so this profile defines six levels. Standards that reference this
// profile should specify one or more of these granularities. If a given
// standard allows more than one granularity, it should specify the meaning of
// the dates and times with reduced precision, for example, the result of
// comparing two dates with different precisions.
// The formats are as follows. Exactly the components shown here must be
// present, with exactly this punctuation. Note that the "T" appears literally
// in the string, to indicate the beginning of the time element, as specified in
// ISO 8601.
// Year:
// YYYY (eg 1997)
// Year and month:
// YYYY-MM (eg 1997-07)
// Complete date:
// YYYY-MM-DD (eg 1997-07-16)
// Complete date plus hours and minutes:
// YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
// Complete date plus hours, minutes and seconds:
// YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
// Complete date plus hours, minutes, seconds and a decimal fraction of a
// second
// YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
// where:
// YYYY = four-digit year
// MM = two-digit month (01=January, etc.)
// DD = two-digit day of month (01 through 31)
// hh = two digits of hour (00 through 23) (am/pm NOT allowed)
// mm = two digits of minute (00 through 59)
// ss = two digits of second (00 through 59)
// s = one or more digits representing a decimal fraction of a second
// TZD = time zone designator (Z or +hh:mm or -hh:mm)
public static Date parse( String input ) throws java.text.ParseException {
//NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
//things a bit. Before we go on we have to repair this.
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd"T"HH:mm:ssz" );
//this is zero time so we need to add that TZ indicator for
if ( input.endsWith( "Z" ) ) {
input = input.substring( 0, input.length() - 1) + "GMT-00:00";
} else {
int inset = 6;
String s0 = input.substring( 0, input.length() - inset );
String s1 = input.substring( input.length() - inset, input.length() );
input = s0 + "GMT" + s1;
}
return df.parse( input );
}
public static String toString( Date date ) {
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd"T"HH:mm:ssz" );
TimeZone tz = TimeZone.getTimeZone( "UTC" );
df.setTimeZone( tz );
String output = df.format( date );
int inset0 = 9;
int inset1 = 6;
String s0 = output.substring( 0, output.length() - inset0 );
String s1 = output.substring( output.length() - inset1, output.length() );
String result = s0 + s1;
result = result.replaceAll( "UTC", "+00:00" );
return result;
}
}
Parses a string representing a date by trying a variety of different parsers.
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>A suite of utilities surrounding the use of the
* {@link java.util.Calendar} and {@link java.util.Date} object.</p>
*
* <p>DateUtils contains a lot of common methods considering manipulations
* of Dates or Calendars. Some methods require some extra explanation.
* The truncate and round methods could be considered the Math.floor(),
* Math.ceil() or Math.round versions for dates
* This way date-fields will be ignored in bottom-up order.
* As a complement to these methods we"ve introduced some fragment-methods.
* With these methods the Date-fields will be ignored in top-down order.
* Since a date without a year is not a valid date, you have to decide in what
* kind of date-field you want your result, for instance milliseconds or days.
* </p>
*
*
*
* @author
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/
public class Main {
//-----------------------------------------------------------------------
/**
* <p>Parses a string representing a date by trying a variety of different parsers.</p>
*
* <p>The parse will try each parse pattern in turn.
* A parse is only deemed sucessful if it parses the whole of the input string.
* If no parse patterns match, a ParseException is thrown.</p>
*
* @param str the date to parse, not null
* @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null
* @return the parsed date
* @throws IllegalArgumentException if the date string or pattern array is null
* @throws ParseException if none of the date patterns were suitable
*/
public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
if (str == null || parsePatterns == null) {
throw new IllegalArgumentException("Date and Patterns must not be null");
}
SimpleDateFormat parser = null;
ParsePosition pos = new ParsePosition(0);
for (int i = 0; i < parsePatterns.length; i++) {
if (i == 0) {
parser = new SimpleDateFormat(parsePatterns[0]);
} else {
parser.applyPattern(parsePatterns[i]);
}
pos.setIndex(0);
Date date = parser.parse(str, pos);
if (date != null && pos.getIndex() == str.length()) {
return date;
}
}
throw new ParseException("Unable to parse the date: " + str, -1);
}
}
Parses a time period into a long. Translates possible [msec|sec|min|h] suffixes
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Map;
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class Main{
/** Millisecond conversion constants */
private static final long MSEC = 1;
private static final long SECS = 1000;
private static final long MINS = 60 * 1000;
private static final long HOUR = 60 * 60 * 1000;
/**
* Parses a time period into a long.
*
* Translates possible [msec|sec|min|h] suffixes
*
* For example:
* "1" -> 1 (msec)
* "1msec -> 1 (msec)
* "1sec" -> 1000 (msecs)
* "1min" -> 60000 (msecs)
* "1h" -> 3600000 (msecs)
*
* Accepts negative periods, e.g. "-1"
*
* @param period the stringfied time period
* @return the parsed time period as long
* @throws NumberFormatException
*/
public static long parseTimePeriod(String period)
{
try
{
String s = period.toLowerCase();
long factor;
// look for suffix
if (s.endsWith("msec"))
{
s = s.substring(0, s.lastIndexOf("msec"));
factor = MSEC;
}
else if (s.endsWith("sec"))
{
s = s.substring(0, s.lastIndexOf("sec"));
factor = SECS;
}
else if (s.endsWith("min"))
{
s = s.substring(0, s.lastIndexOf("min"));
factor = MINS;
}
else if (s.endsWith("h"))
{
s = s.substring(0, s.lastIndexOf("h"));
factor = HOUR;
}
else
{
factor = 1;
}
return Long.parseLong(s) * factor;
}
catch (RuntimeException e)
{
// thrown in addition when period is "null"
throw new NumberFormatException("For input time period: "" + period + """);
}
}
/**
* Same like parseTimePeriod(), but guards for negative entries.
*
* @param period the stringfied time period
* @return the parsed time period as long
* @throws NumberFormatException
*/
public static long parsePositiveTimePeriod(String period)
{
long retval = parseTimePeriod(period);
if (retval < 0)
{
throw new NumberFormatException("Negative input time period: "" + period + """);
}
return retval;
}
}
Perform date validations
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* <p>Perform date validations.</p>
* <p>
* This class is a Singleton; you can retrieve the instance via the
* getInstance() method.
* </p>
*
* @version $Revision: 478334 $ $Date: 2006-11-22 21:31:54 +0000 (Wed, 22 Nov 2006) $
* @since Validator 1.1
*/
public class DateValidator {
/**
* Singleton instance of this class.
*/
private static final DateValidator DATE_VALIDATOR = new DateValidator();
/**
* Returns the Singleton instance of this validator.
* @return A singleton instance of the DateValidator.
*/
public static DateValidator getInstance() {
return DATE_VALIDATOR;
}
/**
* Protected constructor for subclasses to use.
*/
protected DateValidator() {
super();
}
/**
* <p>Checks if the field is a valid date. The pattern is used with
* <code>java.text.SimpleDateFormat</code>. If strict is true, then the
* length will be checked so "2/12/1999" will not pass validation with
* the format "MM/dd/yyyy" because the month isn"t two digits.
* The setLenient method is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param datePattern The pattern passed to <code>SimpleDateFormat</code>.
* @param strict Whether or not to have an exact match of the datePattern.
* @return true if the date is valid.
*/
public boolean isValid(String value, String datePattern, boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.length() <= 0) {
return false;
}
SimpleDateFormat formatter = new SimpleDateFormat(datePattern);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
if (strict && (datePattern.length() != value.length())) {
return false;
}
return true;
}
/**
* <p>Checks if the field is a valid date. The <code>Locale</code> is
* used with <code>java.text.DateFormat</code>. The setLenient method
* is set to <code>false</code> for all.</p>
*
* @param value The value validation is being performed on.
* @param locale The locale to use for the date format, defaults to the default
* system default if null.
* @return true if the date is valid.
*/
public boolean isValid(String value, Locale locale) {
if (value == null) {
return false;
}
DateFormat formatter = null;
if (locale != null) {
formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale);
} else {
formatter =
DateFormat.getDateInstance(
DateFormat.SHORT,
Locale.getDefault());
}
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
return true;
}
}