1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 20 package org.apache.guacamole.form; 21 22 import java.text.DateFormat; 23 import java.text.ParseException; 24 import java.text.SimpleDateFormat; 25 import java.util.Date; 26 27 /** 28 * Represents a time field. The field may contain only time values which 29 * conform to a standard pattern, defined by TimeField.FORMAT. 30 */ 31 public class TimeField extends Field { 32 33 /** 34 * The time format used by time fields, compatible with SimpleDateFormat. 35 */ 36 public static final String FORMAT = "HH:mm:ss"; 37 38 /** 39 * Creates a new TimeField with the given name. 40 * 41 * @param name 42 * The unique name to associate with this field. 43 */ TimeField(String name)44 public TimeField(String name) { 45 super(name, Field.Type.TIME); 46 } 47 48 /** 49 * Parses the given string into a corresponding time. The string must 50 * follow the standard format used by time fields, as defined by 51 * FORMAT and as would be produced by format(). 52 * 53 * @param timeString 54 * The time string to parse, which may be null. 55 * 56 * @return 57 * The time corresponding to the given time string, or null if the 58 * provided time string was null or blank. 59 * 60 * @throws ParseException 61 * If the given time string does not conform to the standard format 62 * used by time fields. 63 */ parse(String timeString)64 public static Date parse(String timeString) 65 throws ParseException { 66 67 // Return null if no time provided 68 if (timeString == null || timeString.isEmpty()) 69 return null; 70 71 // Parse time according to format 72 DateFormat timeFormat = new SimpleDateFormat(TimeField.FORMAT); 73 return timeFormat.parse(timeString); 74 75 } 76 77 /** 78 * Converts the given time into a string which follows the format used by 79 * time fields. 80 * 81 * @param time 82 * The time value to format, which may be null. 83 * 84 * @return 85 * The formatted time, or null if the provided time was null. 86 */ format(Date time)87 public static String format(Date time) { 88 DateFormat timeFormat = new SimpleDateFormat(TimeField.FORMAT); 89 return time == null ? null : timeFormat.format(time); 90 } 91 92 } 93