Here you can find the source of parseTime(String time)
Parameter | Description |
---|---|
time | String representation of Date |
Parameter | Description |
---|---|
ParseException | when String is not valid Date representation |
public static Date parseTime(String time) throws ParseException
//package com.java2s; //License from project: Open Source License import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static Pattern datePattern = null; /**//from ww w . j a v a 2s. co m * Returns Date from specified String time representation. String * representations must be in format YYYY-MM-DD HH:MM:SS (YYYY-year, * MM-month, DD-day; HH-hour, MM-minutes, SS-seconds). * * @param time * String representation of Date * @return Date from String time representation * @throws ParseException * when String is not valid Date representation */ public static Date parseTime(String time) throws ParseException { if (datePattern == null) { datePattern = Pattern.compile("([0-9]{4})-([0-9]{2})-([0-9]{2}).([0-9]{2}):([0-9]{2}):([0-9]{2})"); } Matcher matcher = datePattern.matcher(time); if (!matcher.matches()) { throw new ParseException("Bad date format [" + time + "]", 0); } try { int year = Integer.parseInt(matcher.group(1)); int month = Integer.parseInt(matcher.group(2)); int day = Integer.parseInt(matcher.group(3)); int hour = Integer.parseInt(matcher.group(4)); int minute = Integer.parseInt(matcher.group(5)); int second = Integer.parseInt(matcher.group(6)); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(year, month - 1, day, hour, minute, second); return cal.getTime(); } catch (NumberFormatException ex) { throw new ParseException("Bad date format [" + time + "]", 0); } } }