Java Date Parse asDate(final Map map, final String key)

Here you can find the source of asDate(final Map map, final String key)

Description

as Date

License

Apache License

Declaration

static Date asDate(final Map<String, Object> map, final String key) 

Method Source Code

//package com.java2s;
/* Utils.java/*from   w w w  . j a va2  s  . co m*/
 *
 * Created: 2012-10-01 (Year-Month-Day)
 * Character encoding: UTF-8
 *
 ****************************************** LICENSE *******************************************
 *
 * Copyright (c) 2012 - 2013 XIAM Solutions B.V. (http://www.xiam.nl)
 *
 * 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.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;
import java.util.Map;

public class Main {
    static Date asDate(final Map<String, Object> map, final String key) {
        final Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof String) {
            try {
                return dateFormat().parse((String) value);
            } catch (ParseException ex) {
                throw illegalArgumentException("'%s' has not a valid Date format: '%s'", key, value);
            }
        }
        throw illegalType(key, value, String.class);
    }

    private static DateFormat dateFormat() {
        return new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss ZZZZZ", Locale.US);
    }

    private static IllegalArgumentException illegalArgumentException(String message, Object... args) {

        return new IllegalArgumentException(args.length == 0 ? message : String.format(message, args));
    }

    private static IllegalArgumentException illegalType(final String key, final Object value,
            final Class<?> expectedType) {

        return illegalArgumentException("'%s' is not of type '%s'. Value = '%s' (%s)", key, expectedType.getName(),
                value, value.getClass().getName());
    }
}

Related

  1. asDate(Date date, String format)
  2. asDate(final long time)
  3. asDate(final String literal)
  4. asDate(String date)
  5. asDate(String param, SimpleDateFormat format)
  6. asDate(String s)