比较实用的一些参考: https://www.cnblogs.com/yaogua/p/8012951.html

                                     https://www.cnblogs.com/aston/p/9053201.html

 

 

DateUtils

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
* *************************************************************************
* 
* <PRE>
*  &#64;ClassName:    : DateUtils 
*
*  &#64;Description:    : 
*
*  &#64;Creation Date   : 14 Feb 2019 11:51:20 AM
*
*  &#64;Author          :  Sea
* 
*
* </PRE>
**************************************************************************
*/
@Slf4j
public class DateUtils {

   public static final String TIME_STAMP_STANDARD = "yyyy-MM-dd HH:mm:ss";
   public static final String STANDARD_NO_BLANK = "yyyyMMddHHmmss";
   public static final String ISO8601_STANDARD = "yyyy-MM-dd'T'HH:mm:ssXXX";
   public static final String TIME_DEFAULT_STANDARD = "yyyy-MM-dd'T'hh:mm:ss.SSSZ";
   public static final String MONGO_ISO_DATE = "yyyy-MM-dd'T'hh:mm:ss.SSSZ";
   public static final String FSU_TIME = "yyyyddMMMHHmm";
   private static final org.slf4j.Logger logger = LoggerFactory.getLogger(DateUtils.class);

   
   /**
    * format :yyyy-MM-dd HH:mm:ss
    * @return
    */
   public static Boolean isDateFormat(String date) {
           DateTimeFormatter dtf = DateTimeFormatter.ofPattern(TIME_STAMP_STANDARD);
           boolean flag = true;
           try {
               //Java 8 新添API 用于解析日期和时间
               LocalDateTime.parse(date, dtf);
           } catch (Exception e) {
               flag = false;
           }
           return flag;
    }
   
   /**
    * @Desc :yyyy-MM-ddHH:mm:ss
    * @return
    */
   public static String getCurrentDate(String timeZone) {
       if(StringUtils.isBlank(timeZone)) {
           return  DateFormatUtils.format(new Date(), TIME_STAMP_STANDARD,TimeZone.getTimeZone("GMT+8"));
       }else 
       {
           return  DateFormatUtils.format(new Date(), TIME_STAMP_STANDARD,TimeZone.getTimeZone(timeZone));
       }
   }



public static Date parse(String strDate,String timeZone, String patten) {
       SimpleDateFormat sdf = new SimpleDateFormat(patten);
       sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
       Date parsedate = null;
       try {
           parsedate = sdf.parse(strDate);
       } catch (ParseException e) {
           logger.error("DateUtils.parse date exception is :{}", e);
           e.printStackTrace();
       }
       return parsedate;
   }
   

   /**
    * 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss
    */
   /**
    * @Desc: 将字符串转日期成Long类型的时间戳
    * @param timestr Long
    * @param patten  : eg:yyyy-MM-dd HH:mm:ss
    * @return
    */
   public static Long convertTimeToLong(String timestr, String patten) {
       Assert.notNull(timestr, "time is null");
       DateTimeFormatter ftf = DateTimeFormatter.ofPattern(patten);
       LocalDateTime parse = LocalDateTime.parse(timestr, ftf);
       return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
   }

   /**
    * @Desc: 将字符串转日期成Long类型的时间戳将Long类型的时间戳转换成String 类型的时间格式,patten 时间格式为: like
    *        yyyy-MM-dd HH:mm:ss
    */
   public static String convertTimeToString(Long time, String patten) {
       Assert.notNull(time, "time is null");
       DateTimeFormatter ftf = DateTimeFormatter.ofPattern(patten);
//       DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern(DateUtils.TIME_STAMP_STANDARD, Locale.CHINA);
       return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
   }

   /**
    * @param date
    * @param timezone
    * @return
    */
   public static String translateTimeZone(Date date, String timezone) {
       TimeZone zone = TimeZone.getTimeZone(timezone);
       String dateStr = DateFormatUtils.format(date, DateUtils.TIME_STAMP_STANDARD, zone);
       return dateStr;
   }
   
   
   /**
     * 
     * @param dateStr 20202-05-20 05:20:00
     * @return  GMT+8 Date
     */
    public static Date str2BJ(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return null;
        }
        try {
            SimpleDateFormat dateFromat = new SimpleDateFormat(TIME_STAMP_STANDARD);
            dateFromat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            Date parsedate = dateFromat.parse(dateStr);
            return parsedate;
        } catch (ParseException e) {
            logger.error("DateUtils.parse date exception is :{}", e);
            e.printStackTrace();
            return null;
        }
    }
   
   /**
    * @param date
    * @param timezone
    * 毫秒数:1503544630000,  北京时间:2017-08-24 11:17:10
    * 毫秒数:1503544630000, 东京时间:2017-08-24 12:17:10
    * 毫秒数:1503544630000, 伦敦时间:2017-08-24 04:17:10
    * @return
 * @throws ParseException 
    */
   public static Date translateTimeZoneDate(Date date, String totimezone) throws ParseException {
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       sdf.setTimeZone(TimeZone.getTimeZone(totimezone));
       String sd = sdf.format(Long.parseLong(String.valueOf(date.getTime())));
       Date data = sdf.parse(sd);
       return data;
   }


/**
* @param datestr
* @param fromTimezone
* @param toTimeZone
* @return
*/
   public static String translateTimeZone(String datestr, String fromTimezone,String toTimeZone) 
   {
       try 
       {
           Assert.notNull(datestr,"date(string) can be null");
           Assert.notNull(fromTimezone,"fromTimezone(string) can be null");
           Assert.notNull(toTimeZone,"toTimeZone (string) can be null");
           SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.TIME_STAMP_STANDARD);
           TimeZone fZone = TimeZone.getTimeZone(fromTimezone);
           Assert.notNull(fZone,"can get time by "+fromTimezone);
           sdf.setTimeZone(fZone);
           Date dateFrom = sdf.parse(datestr);
           TimeZone toZone = TimeZone.getTimeZone(toTimeZone);
           Assert.notNull(toZone,"can get time by "+toZone);
           return DateFormatUtils.format(dateFrom, DateUtils.TIME_STAMP_STANDARD,toZone);
       } catch (Exception e) 
       {
           System.err.println("Can't parse current date : {}"+ datestr);
           e.printStackTrace();
           return null;
       }
   }
   


   /**
    * 
    * @param time
    * @return
    */
   public static String before30Day(String time) {
       DateFormat dateFromat = new SimpleDateFormat(TIME_STAMP_STANDARD);
       try {
           Date parse = dateFromat.parse(time);

           Calendar cal = Calendar.getInstance();// get a calendar by using default timezone and language
           cal.setTime(parse);
           cal.add(Calendar.DAY_OF_MONTH, -30);
           Date date = cal.getTime();
           return dateFromat.format(date);

       } catch (ParseException e) {
           e.printStackTrace();
       }
       return null;
   }

   public static String getBeiJingDateLoc() {
       Date date = new Date(System.currentTimeMillis());
       SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_STAMP_STANDARD);
       dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
       return dateFormat.format(date);
   }

   
  
   public static long timeDiffDay(String from,String to) {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = LocalDateTime.parse(from, formatter);
        LocalDateTime endDate = LocalDateTime.parse(to, formatter);
       long min = ChronoUnit.DAYS.between(startDate,endDate);
       return min;
   }
   
   /**
    * Date  to  LocalDateTime  UTC
    * @param date
    * @return
    */
    public static LocalDateTime dateConvertToLocalDateTime(Date date) {
           return date.toInstant().atOffset(ZoneOffset.UTC).toLocalDateTime();
      }
   
  //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
   public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
       return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
   }

   
   /**
     * Get GMT time from current server
     * 
     * @param date
     * @return
     */
    public static Date getGMTDate(Date date) {
        SimpleDateFormat sdfGMT = new SimpleDateFormat(TIME_STAMP_STANDARD);
        sdfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
        SimpleDateFormat sdfLocal = new SimpleDateFormat(TIME_STAMP_STANDARD);
        Date gmtDate = null;
        try {
            gmtDate = sdfLocal.parse(sdfGMT.format(date));
        } catch (ParseException e) {
            log.error("In DateUtil.getGMTDate(), get parse exception: ", e);
        }
        return gmtDate;
    }
    

    
    
    /**
     * Get GMT time from current server
     * 
     * @param date
     * @return
     */
    public static Date getGMT8Date(Date date) {
        SimpleDateFormat sdfGMT = new SimpleDateFormat(TIME_STAMP_STANDARD);
        sdfGMT.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        SimpleDateFormat sdfLocal = new SimpleDateFormat(TIME_STAMP_STANDARD);
        Date gmtDate = null;
        try {
            gmtDate = sdfLocal.parse(sdfGMT.format(date));
        } catch (ParseException e) {
            log.error("In DateUtil.getGMTDate(), get parse exception: ", e);
        }
        return gmtDate;
    }

    /**
     * Convert time resolved from FSU, FSU_TIME -> TIME_STAMP_STANDARD
     *
     * @param datestr
     * @return
     */
    public static String translateFsuTimeToStandard(String datestr) {
        DateFormat dateFormat = new SimpleDateFormat(TIME_STAMP_STANDARD);
        try {
            Date fsuDate = new SimpleDateFormat(FSU_TIME, Locale.ENGLISH).parse(datestr);
            return dateFormat.format(fsuDate);
        } catch (ParseException e) {
            log.error("DateUtils.parse date exception is :{}", e);
            e.printStackTrace();
        }
        return null;
    }
}

 

posted on 2018-09-01 16:54  lshan  阅读(223)  评论(0编辑  收藏  举报