Java Parse Date parseDate(String sdate, String timeFormat, String timeZone)

Here you can find the source of parseDate(String sdate, String timeFormat, String timeZone)

Description

parse Date

License

Apache License

Declaration

public static Date parseDate(String sdate, String timeFormat, String timeZone) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class Main {
    public static final String ISO_DATETIME = "yyyy-MM-dd HH:mm";
    private static final ThreadLocal<Map<String, SimpleDateFormat>> dateFormatterCache = new ThreadLocal<Map<String, SimpleDateFormat>>() {

        @Override//  w w w.  j  a v a2  s.  c om
        protected Map<String, SimpleDateFormat> initialValue() {
            return new HashMap<String, SimpleDateFormat>();
        }
    };

    public static Date parseDate(String sdate, String timeFormat, String timeZone) {
        SimpleDateFormat sdf = getDateFormatter(timeFormat);
        TimeZone ltz = TimeZone.getDefault();
        Date date;
        try {
            date = sdf.parse(sdate);
        } catch (ParseException pe) {
            throw new RuntimeException("Cannot parse date: " + sdate + "; " + pe.getMessage(), pe);
        }
        Date nd = date;
        TimeZone tz = TimeZone.getTimeZone(timeZone);
        if (ltz.hasSameRules(tz) == false) {
            long lo = ltz.getRawOffset();
            long to = tz.getRawOffset();
            nd = new Date(date.getTime() - to + lo);
        }
        return nd;
    }

    public static SimpleDateFormat getDateFormatter(String tfs) {
        Map<String, SimpleDateFormat> m = dateFormatterCache.get();
        if (m.containsKey(tfs) == true) {
            return m.get(tfs);
        }
        try {
            SimpleDateFormat sd = new SimpleDateFormat(tfs);
            m.put(tfs, sd);
            return sd;
        } catch (Exception ex) {
            // TODO gwiki warn
            return getDateFormatter(ISO_DATETIME);
        }

    }
}

Related

  1. parseDate(String sDate)
  2. parseDate(String sDate, Locale locale)
  3. parseDate(String sDate, SimpleDateFormat _dateFormat)
  4. parseDate(String sDate, String sFormat)
  5. parseDate(String sDate, String sSourceFormat, String sDestinationFormat)
  6. parseDate(String sDateTime, String sPattern)
  7. parseDate(String source, String format)
  8. parseDate(String src, String pattern)
  9. parseDate(String srtDate, String pattern)