1   /*
2    * Copyright 2004 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package com.ancientprogramming.fixedformat4j.format.impl;
17  
18  import com.ancientprogramming.fixedformat4j.annotation.Align;
19  import com.ancientprogramming.fixedformat4j.format.FormatInstructions;
20  import com.ancientprogramming.fixedformat4j.format.FixedFormatter;
21  import com.ancientprogramming.fixedformat4j.format.data.FixedFormatPatternData;
22  import junit.framework.Assert;
23  import junit.framework.TestCase;
24  
25  import java.util.Calendar;
26  import java.util.Date;
27  
28  /**
29   * @author Jacob von Eyben - http://www.ancientprogramming.com
30   * @since 1.0.0
31   */
32  public class TestDateFormatter extends TestCase {
33  
34    public FixedFormatter formatter = new DateFormatter();
35  
36    public void testParse() {
37      Assert.assertEquals(getDate(1979, 10, 13), formatter.parse("13101979", new FormatInstructions(8, Align.LEFT, ' ', new FixedFormatPatternData("ddMMyyyy"), null, null, null)));
38      Assert.assertEquals(null, formatter.parse("        ", new FormatInstructions(8, Align.LEFT, ' ', new FixedFormatPatternData("ddMMyyyy"), null, null, null)));
39    }
40  
41    public void testFormat() {
42      Assert.assertEquals("10032008", formatter.format(getDate(2008, 3, 10), new FormatInstructions(8, Align.LEFT, ' ', new FixedFormatPatternData("ddMMyyyy"), null, null, null)));
43      Assert.assertEquals("08", formatter.format(getDate(2008, 3, 10), new FormatInstructions(2, Align.LEFT, ' ', new FixedFormatPatternData("yy"), null, null, null)));
44      Assert.assertEquals("  ", formatter.format(null, new FormatInstructions(2, Align.LEFT, ' ', new FixedFormatPatternData("yy"), null, null, null)));
45    }
46  
47    public Date getDate(int year, int month, int day) {
48      Calendar cal = Calendar.getInstance();
49      cal.set(Calendar.YEAR, year);
50      cal.set(Calendar.MONTH, month - 1);
51      cal.set(Calendar.DAY_OF_MONTH, day);
52      cal.set(Calendar.HOUR_OF_DAY, 0);
53      cal.set(Calendar.MINUTE, 0);
54      cal.set(Calendar.SECOND, 0);
55      cal.set(Calendar.MILLISECOND, 0);
56      return cal.getTime();
57    }
58  }