Simple trick to convert Date format with timezone in Java!

I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format.  Here is my little trick to solve this nuisance.
 

Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list.  Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use javax.xml.bind.DatatypeConverter.parseDateTime(date) to try it and see if that work.

 

Here is my DateUtils.java


package org.cnci.util;
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
 
public abstract class DateUtils {
    // XML formater: this only for converting date into XML string
    private static final SimpleDateFormat xmlFormater =
                           new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
 
    // define all known date formats
    private static final SimpleDateFormat[] allFormats = new SimpleDateFormat[] {
        //new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS a"),
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), // XSD
        new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ"), // Oracle
        new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"),
        new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"), // rfc822
        new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US),
        new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"), // XSD
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"),
        new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS"),
        new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"), // Oracle
        new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"),
        new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"),
        new SimpleDateFormat("yyyy.MM.dd GGG hh:mm aaa"),
        new SimpleDateFormat("yy-MM-dd HH:mm:ss.SSS"),
        new SimpleDateFormat("M/d/yyyy hh:mm:ss"),
        new SimpleDateFormat("M/d/yyyy hh:mm a"),
        new SimpleDateFormat("M/d/yy hh:mm:ss"),
        new SimpleDateFormat("M/d/yy hh:mm a"),
        new SimpleDateFormat("M/d/yy HH:mm"),
        new SimpleDateFormat("M/d/yyyy HH:mm"),
        new SimpleDateFormat("M-d-yy HH:mm"),
        new SimpleDateFormat("M-d-yyyy HH:mm"),
        new SimpleDateFormat("M/d/yy"),
        new SimpleDateFormat("M/d/yyyy"),
        new SimpleDateFormat("M-d-yy"),
        new SimpleDateFormat("M-d-yyyy"),
        new SimpleDateFormat("MMMM d, yyyyy"),
        new SimpleDateFormat("MMM d, yyyyy")
    };
 
    //-----------------------------------------------------------------------
    public static Date parseDate(final String date) throws ParseException {
        if (isEmptyString(date))
            throw new ParseException("Error: date is null or empty!", 0);
 
        // iterate over the array and parse
        Date myDate = null;
        if (date.endsWith("Z")) {
            myDate = parseXMLDate(date);
        }
        if (myDate == null) {
            for (DateFormat df : allFormats) {
                try {
                    myDate = df.parse(date);
                    return myDate;
                }
                catch (Exception e) {
                    // do nothing because we want to try the next
                    // format if current one fails
                }
            }
            if (myDate == null) {
                myDate = parseXMLDate(date);
            }
            // nothing returned so couldn't parse
            if (myDate == null) throw new ParseException("Error: unable to parse date: " + date, 0);
        }
        return myDate;
    }
 
    //Use the JAXB data type conversion, since it already know the xml valid date format
    private static java.util.Date parseXMLDate(final String date) {
        Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime(date);
        return cal.getTime();
    }
     
    //convert to the string representation of the datetime format
    //NOTES: this should be the same as formatDate() but keep
    // and preferred to use this one instead.  Just in case the JAXB
    // document DatetypeConverter change in the future.
    public static String formatXMLDate(final java.util.Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return javax.xml.bind.DatatypeConverter.printDateTime(cal);
    }
     
    // should yield the same results as formatXMLDate() method above.
    public static String formatDate(final java.util.Date date) {
        return xmlFormater.format(date);
    }
     
    public static boolean isEmptyString(String str)
    {
        if (str == null) return true;
        return "".equals(str.trim());
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欧米优

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值