1. 程式人生 > >常用的日期時間操作工具

常用的日期時間操作工具

本文是在開發中經常會使用的日期時間操作類

public class AppsDateUtil {

    private static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static String getStringFromDate(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT,Locale.CHINA);
        String dateStr = sdf.format(date);
        return
dateStr; } public static Date getDateFromString(String string){ SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT,Locale.CHINA); Date date = null; try { date = sdf.parse(string); } catch (ParseException e) { e.printStackTrace(); } return
date; } public static String getStringFromDate(Date date,String template){ SimpleDateFormat sdf = new SimpleDateFormat(template,Locale.CHINA); String dateStr = sdf.format(date); return dateStr; } public static Date getDateFromString(String string,String template){ SimpleDateFormat sdf =
new SimpleDateFormat(template,Locale.CHINA); Date date = null; try { date = sdf.parse(string); } catch (ParseException e) { e.printStackTrace(); } return date; } public static String getStringFromDateString(String date,int length){ try{ String subString = date.substring(0,length); return subString; }catch(Exception ex){ ex.printStackTrace(); } return ""; } public static long getTimeIntervalFromString(String date){ Date d = getDateFromString(date); return d.getTime(); } public static long getTimeIntervalFromString(String date,String dateFormat){ Date d = getDateFromString(date,dateFormat); return d.getTime(); } public static boolean within(String date,long timeGap){ Date d1 = new Date(); Date d2 = getDateFromString(date,"yyyy-MM-dd"); if(d1.getTime() - d2.getTime() < timeGap){ return true; } return false; } public static String timeStampString(){ Date now = new Date(); String s = getStringFromDate(now,"yyyyMMddHHmmss"); return s; } public static String getCurrentTime(String format) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault()); String currentTime = sdf.format(date); return currentTime; } public static String getCurrentTime() { return getCurrentTime("yyyy-MM-dd HH:mm:ss"); } }