Java Hour Format formatDate(Date date, String timeFormat, String timeZone)

Here you can find the source of formatDate(Date date, String timeFormat, String timeZone)

Description

format Date

License

Apache License

Declaration

public static String formatDate(Date date, String timeFormat, String timeZone) 

Method Source Code

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

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/*from   w ww  .j  a  v a 2  s  . com*/
        protected Map<String, SimpleDateFormat> initialValue() {
            return new HashMap<String, SimpleDateFormat>();
        }
    };

    public static String formatDate(Date date, String timeFormat, String timeZone) {
        SimpleDateFormat sdf = getDateFormatter(timeFormat);
        TimeZone ltz = TimeZone.getDefault();
        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() - lo + to);
        }
        return sdf.format(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. formatDate(Date date, String format)
  2. formatDate(Date date, String format, Locale locale)
  3. formatDate(Date date, String patter)
  4. formatDate(Date date, String pattern)
  5. formatDate(Date date, String pattern)
  6. formatDate(Date date, StringBuffer buffer)
  7. formatDate(Date date, TimeZone tz)
  8. formatDate(Date dateString)
  9. formatDate(Date src, String formatPattern)