001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.util.convert.converter; 018 019import java.util.Calendar; 020import java.util.Date; 021import java.util.Locale; 022 023import org.apache.wicket.util.convert.IConverter; 024import org.apache.wicket.util.lang.Args; 025 026/** 027 * Converts to {@link Calendar}. 028 */ 029public class CalendarConverter implements IConverter<Calendar> 030{ 031 private static final long serialVersionUID = 1L; 032 033 private final IConverter<Date> dateConverter; 034 035 /** 036 * Construct. 037 */ 038 public CalendarConverter() 039 { 040 this(new DateConverter()); 041 } 042 043 /** 044 * Construct. 045 * 046 * @param dateConverter 047 * delegated converter, not null 048 */ 049 public CalendarConverter(IConverter<Date> dateConverter) 050 { 051 Args.notNull(dateConverter, "dateConverter"); 052 053 this.dateConverter = dateConverter; 054 } 055 056 @Override 057 public Calendar convertToObject(final String value, final Locale locale) 058 { 059 Date date = dateConverter.convertToObject(value, locale); 060 if (date == null) 061 { 062 return null; 063 } 064 065 Calendar calendar = locale != null ? Calendar.getInstance(locale) : Calendar.getInstance(); 066 calendar.setTime(date); 067 return calendar; 068 } 069 070 @Override 071 public String convertToString(final Calendar value, final Locale locale) 072 { 073 if (value == null) 074 { 075 return null; 076 } 077 return dateConverter.convertToString(value.getTime(), locale); 078 } 079}