面試題1 -- Java 中,怎麼在格式化的日期中顯示時區?

使用SimpleDateFormat來實現格式化日期

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatExample {

    public static void main(String args[]) {

        Date today = new Date();

        System.out.println("今天 is : " + today);

        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
        String date = DATE_FORMAT.format(today);
        System.out.println("今天 in dd-MM-yyyy format : " + date);

        DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
        date = DATE_FORMAT.format(today);
        System.out.println("今天 in dd/MM/yy pattern : " + date);

        //formatting Date with time information
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
        date = DATE_FORMAT.format(today);
        System.out.println("今天 in dd-MM-yy:HH:mm:SS : " + date);

        //SimpleDateFormat example - Date with timezone information
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
        date = DATE_FORMAT.format(today);
        System.out.println("今天 in dd-MM-yy:HH:mm:SSZ : " + date);

    }

}
可是

DateFormat 的全部實現,包括 SimpleDateFormat 都不是線程安全的,所以你不該該在多線程序中使用,除非是在對外線程安全的環境中使用,如 將 SimpleDateFormat 限制在 ThreadLocal 中。若是你不這麼作,在解析或者格式化日期的時候,可能會獲取到一個不正確的結果。所以,從日期、時間處理的全部實踐來講,我強力推薦 joda-time 庫。
java

 

Joda-Time

主要的特色包括:

1. 易於使用:Calendar讓獲取"正常的"的日期變得很困難,使它沒辦法提供簡單的方法,而Joda-Time可以 直接進行訪問域而且索引值1就是表明January。
2. 易於擴展:JDK支持多日曆系統是經過Calendar的子類來實現,這樣就顯示的很是笨重並且事實 上要實現其它日曆系統是很困難的。Joda-Time支持多日曆系統是經過基於Chronology類的插件體系來實現。
安全

3. 提供一組完整的功能:它打算提供 全部關係到date-time計算的功能.Joda-Time當前支持8種日曆系統,並且在未來還會繼續添加,有着比JDK Calendar更好的總體性能等等。多線程

封裝joda-time的時間工具類:工具

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

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.Days;
import org.joda.time.LocalDate;

import com.sun.istack.internal.Nullable;

/**
 * 使用joda的時間工具類
 * @author soyoungboy
 *
 */
public class DateUtils {

    public static final long SECOND = 1000; // 1秒 java已毫秒爲單位

    public static final long MINUTE = SECOND * 60; // 一分鐘

    public static final long HOUR = MINUTE * 60; // 一小時

    public static final long DAY = HOUR * 24; // 一天

    public static final long WEEK = DAY * 7; // 一週

    public static final long YEAR = DAY * 365; // 一年

    public static final String FORMAT_TIME = "yyyy-MM-dd HH:mm:ss"; // 默認時間格式

    public static final String FORMAT_TIME_MINUTE = "yyyy-MM-dd HH:mm"; // 默認時間格式

    public static final String FORTER_DATE = "yyyy-MM-dd"; // 默認日期格式

    private static final Map<Integer, String> WEEK_DAY = new HashMap<Integer, String>();
    static {
        WEEK_DAY.put(7, "星期六");
        WEEK_DAY.put(1, "星期天");
        WEEK_DAY.put(2, "星期一");
        WEEK_DAY.put(3, "星期二");
        WEEK_DAY.put(4, "星期三");
        WEEK_DAY.put(5, "星期四");
        WEEK_DAY.put(6, "星期五");
    }

    /**
     * 獲取當前系統時間
     * 
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getCurrentTime() {
        DateTime dt = new DateTime();
        String time = dt.toString(FORMAT_TIME);
        return time;
    }

    /**
     * 獲取系統當前時間按照指定格式返回
     * 
     * @param pattern
     *            yyyy/MM/dd hh:mm:a
     * @return
     */
    public static String getCurrentTimePattern(String pattern) {
        DateTime dt = new DateTime();
        String time = dt.toString(pattern);
        return time;
    }

    /**
     * 獲取當前日期
     * 
     * @return
     */
    public static String getCurrentDate() {
        DateTime dt = new DateTime();
        String date = dt.toString(FORTER_DATE);
        return date;
    }

    /**
     * 獲取當前日期按照指定格式
     * 
     * @param pattern
     * @return
     */
    public static String getCurrentDatePattern(String pattern) {
        DateTime dt = new DateTime();
        String date = dt.toString(pattern);
        return date;
    }

    /**
     * 按照時區轉換時間
     * 
     * @param date
     * @param timeZone
     *            時區
     * @param parrten
     * @return
     */
    @Nullable
    public static String format(Date date, TimeZone timeZone, String parrten) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(parrten);
        sdf.setTimeZone(timeZone);
        return sdf.format(date);
    }

    /**
     * 獲取指定時間
     * 
     * @param year
     *            年
     * @param month
     *            月
     * @param day
     *            天
     * @param hour
     *            小時
     * @param minute
     *            分鐘
     * @param seconds
     *            秒
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getPointTime(Integer year, Integer month, Integer day, Integer hour, Integer minute,
            Integer seconds) {
        DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
        String date = dt.toString(FORMAT_TIME);
        return date;
    }

    /**
     * 
     * @param year
     *            年
     * @param month
     *            月
     * @param day
     *            天
     * @param hour
     *            小時
     * @param minute
     *            分鐘
     * @param seconds
     *            秒
     * @param parrten
     *            自定義格式
     * @return parrten
     */
    public static String getPointTimePattern(Integer year, Integer month, Integer day, Integer hour, Integer minute,
            Integer seconds, String parrten) {
        DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
        String date = dt.toString(parrten);
        return date;
    }

    /**
     * 獲取指定日期
     * 
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String getPointDate(Integer year, Integer month, Integer day) {
        LocalDate dt = new LocalDate(year, month, day);
        String date = dt.toString(FORTER_DATE);
        return date;
    }

    /**
     * 獲取指定日期 返回指定格式
     * 
     * @param year
     * @param month
     * @param day
     * @param parrten
     * @return
     */
    public static String getPointDatParrten(Integer year, Integer month, Integer day, String parrten) {
        LocalDate dt = new LocalDate(year, month, day);
        String date = dt.toString(parrten);
        return date;
    }

    /**
     * 獲取當前是一週星期幾
     * 
     * @return
     */
    public static String getWeek() {
        DateTime dts = new DateTime();
        String week = null;
        switch (dts.getDayOfWeek()) {
        case DateTimeConstants.SUNDAY:
            week = "星期日";
            break;

        case DateTimeConstants.MONDAY:
            week = "星期一";
            break;

        case DateTimeConstants.TUESDAY:
            week = "星期二";
            break;
        case DateTimeConstants.WEDNESDAY:
            week = "星期三";
            break;
        case DateTimeConstants.THURSDAY:
            week = "星期四";
            break;
        case DateTimeConstants.FRIDAY:
            week = "星期五";
            break;
        case DateTimeConstants.SATURDAY:
            week = "星期六";
        default:
            break;
        }
        return week;
    }

    /**
     * 獲取指定時間是一週的星期幾
     * 
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String getWeekPoint(Integer year, Integer month, Integer day) {
        LocalDate dts = new LocalDate(year, month, day);
        String week = null;
        switch (dts.getDayOfWeek()) {
        case DateTimeConstants.SUNDAY:
            week = "星期日";
            break;
        case DateTimeConstants.MONDAY:
            week = "星期一";
            break;
        case DateTimeConstants.TUESDAY:
            week = "星期二";
            break;
        case DateTimeConstants.WEDNESDAY:
            week = "星期三";
            break;
        case DateTimeConstants.THURSDAY:
            week = "星期四";
            break;
        case DateTimeConstants.FRIDAY:
            week = "星期五";
            break;
        case DateTimeConstants.SATURDAY:
            week = "星期六";
            break;

        default:
            break;
        }
        return week;
    }

    /**
     * 格式化日期
     * 
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    @Nullable
    public static String format(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);
        return format.format(date);
    }

    /**
     * 格式化日期字符串
     * 
     * @param date
     *            日期
     * @param pattern
     *            日期格式
     * @return
     */
    @Nullable
    public static String format(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * 解析日期
     * 
     * @param date
     *            日期字符串
     * @param pattern
     *            日期格式
     * @return
     */
    @Nullable
    public static Date parse(String date, String pattern) {
        if (date == null) {
            return null;
        }
        Date resultDate = null;
        try {
            resultDate = new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {

        }
        return resultDate;
    }

    /**
     * 解析日期yyyy-MM-dd HH:mm:ss
     * 
     * @param date
     *            日期字符串
     * @return
     */
    @Nullable
    public static Date parse(String date) {
        if (date == null) {
            return null;
        }

        try {
            return new SimpleDateFormat(FORMAT_TIME).parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 解析日期 yyyy-MM-dd HH:mm:ss
     * 
     * @param timestamp
     * @return
     */
    public static String format(Long timestamp, String pattern) {
        String dateStr = "";
        if (null == timestamp || timestamp.longValue() < 0) {
            return dateStr;
        }
        try {
            Date date = new Date(timestamp);
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            dateStr = format.format(date);
        } catch (Exception e) {
            // ignore
        }

        return dateStr;
    }

    /**
     * 解析日期 yyyy-MM-dd HH:mm:ss
     * 
     * @param timestamp
     * @return
     */
    public static String format(Long timestamp) {
        String dateStr = "";
        if (null == timestamp || timestamp.longValue() < 0) {
            return dateStr;
        }
        try {
            Date date = new Date(timestamp);
            SimpleDateFormat format = new SimpleDateFormat(FORMAT_TIME);
            dateStr = format.format(date);
        } catch (Exception e) {
            // ignore
        }

        return dateStr;
    }

    /**
     * 獲取當前時間前幾天時間,按指定格式返回
     * 
     * @param days
     * @return
     */
    public static String forwardDay(Integer days, String format) {
        DateTime dt = new DateTime();
        DateTime y = dt.minusDays(days);
        return y.toString(format);
    }

    /**
     * 獲取當前時間前幾天時間
     * 
     * @param days
     * @return
     */
    public static Date forwardDay(Integer days) {
        DateTime dt = new DateTime();
        DateTime y = dt.minusDays(days);
        return y.toDate();
    }

    /**
     * 獲取指定時間以後或者以前的某一天00:00:00 默認返回當天
     * 
     * @param days
     * @return
     */
    public static Date day00(Integer days, String date, String zimeZone) throws Throwable {
        DateTime dt;
        TimeZone timeZone;
        try {
            if (isBlank(zimeZone)) {
                timeZone = TimeZone.getDefault();
            } else {
                timeZone = TimeZone.getTimeZone(zimeZone);
            }
            if (isBlank(date)) {
                dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            } else {
                dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            }
        } catch (Exception e) {
            throw new Throwable(e);
        }

        DateTime y = dt.minusDays(days).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        return y.toDate();
    }

    /**
     * 獲取指定時間以後或者以前的某一天23:59:59 默認返回當天
     * 
     * @param days
     *            偏移量
     * @return
     */
    public static Date day59(Integer days, String date, String zimeZone) throws Throwable {
        DateTime dt;
        TimeZone timeZone;
        try {
            if (isBlank(zimeZone)) {
                timeZone = TimeZone.getDefault();
            } else {
                timeZone = TimeZone.getTimeZone(zimeZone);
            }
            if (isBlank(date)) {

                dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            } else {
                dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            }
        } catch (Exception e) {
            throw new Throwable(e);
        }
        DateTime y = dt.minusDays(days).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
        return y.toDate();
    }

    /**
     * 計算兩個時間相差多少天
     * 
     * @param startDate
     * @param endDate
     * @return
     */
    @Nullable
    public static Integer diffDay(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return null;
        }
        DateTime dt1 = new DateTime(startDate);
        DateTime dt2 = new DateTime(endDate);
        int day = Days.daysBetween(dt1, dt2).getDays();
        return Math.abs(day);
    }

    /**
     * 獲取某月以前,以後某一個月最後一天,24:59:59
     * 
     * @return
     */
    public static Date lastDay(Date date, Integer month) {
        DateTime dt1;
        if (month == null) {
            month = 0;
        }
        if (date == null) {
            dt1 = new DateTime().minusMonths(month);
        } else {
            dt1 = new DateTime(date).minusMonths(month);
        }
        DateTime lastDay = dt1.dayOfMonth().withMaximumValue().withHourOfDay(23).withMinuteOfHour(59)
                .withSecondOfMinute(59);
        return lastDay.toDate();
    }

    /**
     * 獲取某月月以前,以後某一個月第一天,00:00:00
     * 
     * @return
     */
    public static Date firstDay(Date date, Integer month) {
        DateTime dt1;
        if (month == null) {
            month = 0;
        }
        if (date == null) {
            dt1 = new DateTime().minusMonths(month);
        } else {
            dt1 = new DateTime(date).minusMonths(month);
        }
        DateTime lastDay = dt1.dayOfMonth().withMinimumValue().withHourOfDay(0).withMinuteOfHour(0)
                .withSecondOfMinute(0);
        return lastDay.toDate();
    }

    public static Date addDay(Date date, int offset) {
        DateTime dt1;
        if (date == null) {
            dt1 = new DateTime().plusDays(offset);
            return dt1.toDate();
        }
        dt1 = new DateTime(date).plusDays(offset);
        return dt1.toDate();

    }

    /**
     * 傳入日期時間與當前系統日期時間的比較, 若日期相同,則根據時分秒來返回 , 不然返回具體日期
     * 
     * @return 日期或者 xx小時前||xx分鐘前||xx秒前
     */
    @Nullable
    public static String getNewUpdateDateString(Date now, Date createDate) {
        if (now == null || createDate == null) {
            return null;
        }
        Long time = (now.getTime() - createDate.getTime());
        if (time > (24 * 60 * 60 * 1000)) {
            return time / (24 * 60 * 60 * 1000) + "天前";
        } else if (time > (60 * 60 * 1000)) {
            return time / (60 * 60 * 1000) + "小時前";
        } else if (time > (60 * 1000)) {
            return time / (60 * 1000) + "分鐘前";
        } else if (time >= 1000) {
            return time / 1000 + "秒前";
        }
        return "剛剛";
    }
    /**
     * 
     * @Title: isBlank
     * @Description: TODO(判斷字符串是否爲空或長度爲0 或由空格組成)
     * @param @param str
     * @param @return 設定文件
     * @return boolean 返回類型
     * @throws
     */
    public static boolean isBlank(String str) {
        return (str == null || str.trim().length() == 0);
    }
    
    public static void main(String[] args) throws Throwable {
         System.out.println(lastDay(new Date(),2));
         System.out.println(firstDay(null,0));
         TimeZone zone1=TimeZone.getTimeZone("GMT+8");
         TimeZone zone2=TimeZone.getTimeZone("GMT-5");
         System.out.println(format(new Date(),zone1,FORMAT_TIME));
         System.out.println(format(new Date(),zone2,FORMAT_TIME));
        
         System.out.println(format(day00(0,"2017-5-11","GMT+0")));
         System.out.println(format(day00(0,"2017-5-11","GMT+8")));
         System.out.println(format(day00(0,"2017-5-11","GMT-8")));
         Date date1 =parse("2017-05-11 17:53:52");
        
         System.out.println(diffDay(date1,new Date()));

         DateTime dateTime = new DateTime().withDayOfWeek(1);
        
         DateTime dateTime1 = new DateTime().withDayOfWeek(7).withTime(0, 0,
         0, 0);
         System.out.println(format(dateTime.toDate()));
        
         System.out.println(format(dateTime1.toDate()));

        System.out.println(format(new Date(), "MM/dd"));
    }

}

其中測試代碼結果:性能

Fri Jun 30 23:59:59 GMT+08:00 2017
Tue Aug 01 00:00:00 GMT+08:00 2017
2017-08-28 19:47:28
2017-08-28 06:47:28
2017-05-10 00:00:00
2017-05-11 00:00:00
2017-05-10 00:00:00
109
2017-08-28 19:47:29
2017-09-03 00:00:00
08/28
相關文章
相關標籤/搜索