码迷,mamicode.com
首页 > 编程语言 > 详细

java常用日期类型转换

时间:2015-06-04 15:32:23      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;

/**
 * @author Simon Lv
 * @since 2012-6-10
 */
public class DateUtils {

    public static final String YYMMDD = "yyMMdd";
    public static final String YYYYMMDD = "yyyyMMdd";
    public static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
    public static final String PATTERN_DATETIME_M = "yyyy-MM-dd HH:mm";
    public static final String PATTERN_DATE = "yyyy-MM-dd";
    public static final String PATTERN_MONTH = "yyyy-MM";
    public static final String YEAR = "yyyy";
    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm:ss");

    public static DateTime toDateTime(String dateTime) {
        if (StringUtils.isBlank(dateTime)) {
            return null;
        }
        return DateTimeFormat.forPattern(PATTERN_DATETIME).parseDateTime(dateTime);
    }
    
    public static DateTime strToDateTime(String dateTime) {
        if (StringUtils.isBlank(dateTime)) {
            return null;
        }
        return DateTimeFormat.forPattern(PATTERN_DATE).parseDateTime(dateTime);
    }

    public static String toString(DateTime dateTime) {
        return dateTime.toString(PATTERN_DATETIME);
    }
    
    public static String dateToString(DateTime dateTime) {
        return dateTime.toString(YEAR);
    }
    public static String dateTimeToString(DateTime dateTime) {
        return dateTime.toString(PATTERN_DATE);
    }

    public static String toString(String dateTime, String pattern) {
        return new DateTime(dateTime).toString(pattern);
    }

    public static String toString(LocalDate localDate, String pattern) {
        if (localDate == null) {
            return null;
        }
        return localDate.toString(pattern);
    }

    public static String todayToString() {
        return new LocalDate().toString(YYMMDD);
    }
    public static String todayToStringYear() {
        return new LocalDate().toString(YEAR);
    }
    public static String todayToString2() {
        return new LocalDate().toString(YYYYMMDD);
    }
    public static String todayToYYYYMMDDStr() {
        return new LocalDate().toString(PATTERN_DATE);
    }
    public static String todayToChinaStr() {
        Calendar calendar =Calendar.getInstance();
        StringBuffer sb = new StringBuffer();
        sb.append(calendar.get(Calendar.YEAR)).append("年")
            .append(calendar.get(Calendar.MONTH)+1).append("月")
            .append(calendar.get(Calendar.DAY_OF_MONTH)).append("日")
            .append(calendar.get(Calendar.HOUR)).append("时")
            .append(calendar.get(Calendar.MINUTE)).append("分");
        
        return sb.toString();
    }
    
    /**
     * 将微信消息中的CreateTime转换成标准格式的时间(yyyy-MM-dd HH:mm:ss)
     * 
     * @param createTime
     * @return
     */
    public static String getNormalDateFromWebChat(String createTime) {
        Long msgCreateTime = Long.parseLong(createTime) * 1000;

        return DATE_FORMAT.format(new Date(msgCreateTime));
    }
    /**
     * 将long型时间格式转换为字符格式
     * 
     * @return 返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String long2LongString(long date){
        if(date == -99){
            return "-";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATETIME);
        return sdf.format(new Date(date));
    }
    
    public static String long2DateString(Long date, String pattern){
        if(date == null || date.longValue() ==0){
            return "-";
        }
        if(date.longValue() == -99){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(new Date(date));
    }
    
    /**
     * 将long型时间格式转换为字符格式
     * 
     * @return 返回字符串格式 yyyy-MM-dd HH:mm
     */
    public static String long2DatemString(long date){
        if(date == -99){
            return "-";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATETIME_M);
        return sdf.format(new Date(date));
    }
    
    /**
     * 将long型时间格式转换为字符格式
     * 
     * @param date
     * @return 返回字符串格式 yyyy-MM-dd
     */
    public static String long2String(Long date){
        if(null == date || date == -99 || date == 0){
            return "-";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE);
        return sdf.format(new Date(date));
    }
    
    /***
     * YYYY-MM-DD
     * @param dateTime
     * @return
     */
    public static long str2Long(String dateTime){
        if (StringUtils.isBlank(dateTime)) {
            return 0l;
        }
        Date date = string2Date(dateTime);
        
        return date.getTime();
    }
    /**
     * yyyy-MM-dd HH:mm:ss
     * @param dateTime
     * @return
     */
    public static long strSLong(String dateTime){
        if (StringUtils.isBlank(dateTime)) {
            return 0l;
        }
        Date date = string2Datetime(dateTime);
        
        return date.getTime();
    }
    
    /**
     * 将DateTime型时间格式转换为long
     * 
     * @param date
     * @return 
     */
    public static long date2Long(DateTime dateTime){
        if (dateTime == null) {
            return 0l;
        }
        String date1 = dateTimeToString(dateTime);
        Date date = string2Date(date1);
        return date.getTime();
    }
    
    
    /**
     * 获得精确到秒的日期类型
     * yyyy-MM-dd HH:mm:ss
     * @param date
     * @return
     */
    public static Date string2Datetime(String date) {
        Date retValue = null ;
        SimpleDateFormat sdf= new SimpleDateFormat(PATTERN_DATETIME);
        try{
            retValue = sdf.parse(date);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retValue;
    }
    
    /**
     * 获得日期类型
     * 
     * @param date
     * @return
     */
    public static Date string2Date(String date) {
        Date retValue = null ;
        SimpleDateFormat sdf= new SimpleDateFormat(PATTERN_DATE);
        try{
            retValue = sdf.parse(date);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retValue;
    }
    
    /**
     * 日期转换为Long
     * 
     * @param dateTime
     * @return
     */
    public static long str2MonthLong(String dateTime){
        if (StringUtils.isEmpty(dateTime)) {
            return 0l;
        }
        Date date = string2MonthDate(dateTime);
        
        return date != null ? date.getTime() : 0l;
    }
    
    /**
     * 获得月份类型
     * 
     * @param date
     * @return
     */
    public static Date string2MonthDate(String date) {
        Date retValue = null ;
        SimpleDateFormat sdf= new SimpleDateFormat(PATTERN_MONTH);
        try{
            retValue = sdf.parse(date);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retValue;
    }
    /***
     * YYYY-MM-DD
     * @param date
     * @return
     */
    public static int getDayOfWeek(String date){
        String[] dateArr = date.split("-");
        int year = Integer.parseInt(dateArr[0]);
        int month = Integer.parseInt(dateArr[1]);
        int day= Integer.parseInt(dateArr[2]);
        Calendar calendar = Calendar.getInstance();//获得一个日历
        calendar.set(year, month-1, day);//设置当前时间,月份是从0月开始计算
        int number = calendar.get(Calendar.DAY_OF_WEEK);//星期表示1-7,是从星期日开始,   
        return number;
    }
    /**
     * 获取指定日期一年前时间
     * 
     * @return 返回long格式 
     */
    public static long getChainYear(long date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(date));
        cal.add(Calendar.YEAR,-1);   
        return cal.getTime().getTime();
    }
    
    /***
     * 时间差,分钟
     * @param startTime
     * @param endTime
     * @return
     */
    public static String timeDifference(long startTime,long endTime ){
        long timeDifferenceSecond = endTime - startTime;
        double dmin = ((double)timeDifferenceSecond/(60*1000));
        BigDecimal bd = BigDecimal.valueOf(dmin);
        DecimalFormat df = new DecimalFormat("0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        return df.format(bd);
    }
    
    public static Date getTimesWeekMoningDate(int h,int m,int s){
        Calendar cal = Calendar.getInstance();        
        int year = cal.get(Calendar.YEAR);
        int monday = cal.get(Calendar.MONDAY);
        int dayOfMonth =  cal.get(Calendar.DAY_OF_MONTH);
        cal.set(year, monday,dayOfMonth, h, m, s);        
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);        
        return cal.getTime();
    }
    /**
     * 本周开始时间 yyyy-MM-dd HH:mm:ss 0点
     * @return
     */
    public static String getTimesWeekMorning() {        
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_DATETIME);
        String dateString = formatter.format(getTimesWeekMoningDate(0,0,0));
        return dateString;
    }
    
    /**
     * 本周结束时间 yyyy-MM-dd HH:mm:ss 24点
     * @return
     */
    public static String getTimesWeekNight() {        
        Calendar cal = Calendar.getInstance();    
        cal.setTime(getTimesWeekMoningDate(0,0,0));        
        cal.add(Calendar.DAY_OF_WEEK, 7);        
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_DATETIME);
        String dateString = formatter.format(cal.getTime());
        return dateString;
    }
    
    
    /***
     * 本月开始时间0点
     * @return
     */
    public static String getTimesMonthMorning() {        
        Calendar cal = Calendar.getInstance();        
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);    
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_DATETIME);
        String dateString = formatter.format(cal.getTime());
        return dateString;
    }
    
    /***
     * 本月结束时间24点
     * @return
     */
    public static String getTimesMonthNight() {        
        Calendar cal = Calendar.getInstance();    
        int year = cal.get(Calendar.YEAR);
        int monday = cal.get(Calendar.MONDAY);
        int dayOfMonth =  cal.get(Calendar.DAY_OF_MONTH);
        cal.set(year, monday,dayOfMonth, 0, 0, 0);        
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));        
        cal.set(Calendar.HOUR_OF_DAY, 24);        
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_DATETIME);
        String dateString = formatter.format(cal.getTime());
        return dateString;    
    }
}

 

java常用日期类型转换

标签:

原文地址:http://www.cnblogs.com/qiuyu-blog/p/4551792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!