/**
* 类描述:时间操作定义类
*/
public class DateUtils{
private static final Logger logger = Logger.getLogger(DateUtils.class);
  // ticks时间格式
//ticksToDatetime
    public static Date ticksToDate(long ticks){
if(ticks == 0){
return null;
}
return new Date((ticks- 621355968000000000l)/10000);
}
//ticksToDatetime
public static String ticksToObject(long ticks,String pattern){
if(ticks == 0){
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date((ticks- 621355968000000000l)/10000));
}   //
SimpleDateFormat 线程安全配置

/** 锁对象 */
private static final Object lockObj = new Object(); /** 存放不同的日期模板格式的sdf的Map */
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>(); /**
* 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
* @param pattern
* @return
*/
private static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
// 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf
if (tl == null) {
synchronized (lockObj) {
tl = sdfMap.get(pattern);
if (tl == null) {
// 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map // 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new SimpleDateFormat
tl = new ThreadLocal<SimpleDateFormat>() { @Override
protected SimpleDateFormat initialValue() { return new SimpleDateFormat(pattern);
}
};
sdfMap.put(pattern, tl);
}
}
}
return tl.get();
}
/**
* 是用ThreadLocal<SimpleDateFormat>来获取SimpleDateFormat,这样每个线程只会有一个SimpleDateFormat
* @param date
* @param pattern
* @return
*/
public static String format(Date date, String pattern) {
return getSdf(pattern).format(date);
}
public static Date parse(String dateStr, String pattern) throws ParseException {
return getSdf(pattern).parse(dateStr);
} /**
* 本地时间转UTC时间
* @param cron cron表达式
* @param timezone 时区
* @return
*/
public static String localToUTC(String cron , int timezone) {
logger.info("===cron==="+cron);
logger.info("===timezone==="+timezone);
String offset = "";
if(timezone<0){
offset = String.valueOf(-(timezone));
}else if(timezone>0){
offset = String.valueOf(-timezone);
}else{
return cron;
}
Date date = new Date();
String crons[] = cron.split(" ");
String time = "";
String newCron = "";
String newTime = "";
logger.info("===length==="+crons.length);
if(crons.length==5){
String hour = crons[1];
String hours [] = hour.split("-");
if(hours.length==1){
String hour0 = hours[0];
if(hours[0].indexOf("/")>-1){
hour0 = hour0.substring(0,hour0.indexOf("/"));
}
if(!isInteger(hour0)){
return cron;
}else{
if("*".equals(crons[4])){
time += getCurrentYear(date)+"-";
}else{
time += crons[4]+"-";
}
if("*".equals(crons[3])){
time += getCurrentMonth(date)+"-";
}else{
time += crons[3]+"-";
}
if("*".equals(crons[2])){
time += getCurrentDay(date)+" ";
}else{
time += crons[2]+" ";
}
time += hour0 + ":" + "00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
logger.info(time);
logger.info("UTC"+offset);
Date date2 = sdf.parse(time);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"+offset));
newTime = sdf.format(date2);
logger.info("====newTime==="+newTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date3 = sdf3.parse(newTime);
if(hours[0].indexOf("/")>-1){
newCron = crons[0]+" "+numberFormat(getCurrentHour(date3))+hours[0].substring(hours[0].indexOf("/"))+" ";
}else{
newCron = crons[0]+" "+numberFormat(getCurrentHour(date3))+" ";
}
if(!"*".equals(crons[2])){
newCron += numberFormat(getCurrentDay(date3))+" ";
}else{
newCron += crons[2]+" ";
}
if(!"*".equals(crons[3])){
newCron += numberFormat(getCurrentMonth(date3))+" ";
}else{
newCron += crons[3]+" ";
}
newCron += crons[4]+" ";
logger.info("====newCron==="+newCron);
return newCron;
}catch (ParseException e){
logger.error(e);
return cron;
}
}
}else{
if(!isInteger(hours[0])){
return cron;
}else{
if("*".equals(crons[4])){
time += getCurrentYear(date)+"-";
}else{
time += crons[4]+"-";
}
if("*".equals(crons[3])){
time += getCurrentMonth(date)+"-";
}else{
time += crons[3]+"-";
}
if("*".equals(crons[2])){
time += getCurrentDay(date)+" ";
}else{
time += crons[2]+" ";
}
time += hours[0] + ":" + "00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String hour0 = "";
try {
logger.info(time);
logger.info("UTC"+offset);
Date date2 = sdf.parse(time);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"+offset));
newTime = sdf.format(date2);
logger.info("====newTime==="+newTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date3 = sdf3.parse(newTime);
hour0 = getCurrentHour(date3);
logger.info("====hour0==="+hour0);
}catch (ParseException e){
logger.error(e);
return cron;
} String hour1 = hours[1];
if(hours[1].indexOf("/")>-1){
hour1 = hour1.substring(0,hour1.indexOf("/"));
}
String time2 = "";
if("*".equals(crons[4])){
time2 += getCurrentYear(date)+"-";
}else{
time2 += crons[4]+"-";
}
if("*".equals(crons[3])){
time2 += getCurrentMonth(date)+"-";
}else{
time2 += crons[3]+"-";
}
if("*".equals(crons[2])){
time2 += getCurrentDay(date)+" ";
}else{
time2 += crons[2]+" ";
}
time2 += hour1 + ":" + "00";
try {
logger.info(time2);
SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date4 = sdf4.parse(time2);
sdf4.setTimeZone(TimeZone.getTimeZone("UTC"+offset));
newTime = sdf4.format(date4);
logger.info("====newTime==="+newTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date3 = sdf3.parse(newTime);
String hour2 = getCurrentHour(date3);
String newHour = "";
logger.info(hours[1]);
if(hours[1].indexOf("/")>-1){
newHour = numberFormat(hour0)+"-"+numberFormat(hour2)+hours[1].substring(hours[1].indexOf("/"));
}else{
newHour = numberFormat(hour0)+"-"+numberFormat(hour2);
}
newCron = crons[0]+" "+newHour+" ";
if(!"*".equals(crons[2])){
newCron += numberFormat(getCurrentDay(date3))+" ";
}else{
newCron += crons[2]+" ";
}
if(!"*".equals(crons[3])){
newCron += numberFormat(getCurrentMonth(date3))+" ";
}else{
newCron += crons[3]+" ";
}
newCron += crons[4]+" ";
logger.info("====newCron==="+newCron);
return newCron;
}catch (ParseException e){
logger.error(e);
return cron;
}
}
}
}else{
return cron;
}
} //去除首位0
public static String numberFormat(String number) {
int num = Integer.parseInt(number);
if(num<10){
number = number.substring(1);
}
return number;
} //获得当前年份
public static String getCurrentYear(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
return sdf.format(date);
} //获得当前月份
public static String getCurrentMonth(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("MM");
return sdf.format(date);
} //获得当前日
public static String getCurrentDay(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("dd");
return sdf.format(date);
} //获得当前时
public static String getCurrentHour(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("HH");
return sdf.format(date);
}
//两时间相减获得时分秒
public static String formatDuration(String startDate ,String endDate){
if(StringUtil.isNotEmpty(startDate) && StringUtil.isNotEmpty(endDate)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化时间
try{
Long start = sdf.parse(startDate).getTime();
Long end = sdf.parse(endDate).getTime();
Long time = end-start;
int seconds = time.intValue()/1000;
return secToTime(seconds);
}catch (ParseException e){
logger.error(e);
return "";
}
}else{
return "";
}
} // 整数(秒数)转换为时分秒
public static String secToTime(int time) {
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0)
second = 0;
else {
minute = time / 60;
if (minute < 60) {
second = time % 60;
} else {
hour = minute / 60;
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
}
}
String h="",m="",s="";
if(hour!=0){
h = hour+"时";
}
if(minute!=0){
m = minute+"分";
}
if(second!=0){
s = second+"秒";
}
return h+m+s;
} }

DateUtil-工具类的更多相关文章

  1. DateUtil工具类

    package com.autoserve.mh.common.util;   import java.text.SimpleDateFormat; import java.util.Calendar ...

  2. 邓博泽 java最全的DateUtil工具类

    package com.kld.yijie.web.util; import org.slf4j.Logger;import org.slf4j.LoggerFactory; import java. ...

  3. 03-自己封装DateUtil工具类

    package com.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.u ...

  4. hutool的DateUtil工具类

    1.0.DateUitl(日期时间) 0)坐标 <dependency> <groupId>cn.hutool</groupId> <artifactId&g ...

  5. hutool包的DateUtil工具类

    [首先引入依赖 ] <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core& ...

  6. JAVA DateUtil 工具类封装(转)

    原文链接 https://blog.csdn.net/wangpeng047/article/details/8295623  作者三次整理后的代码 下载链接   https://www.lanzou ...

  7. JAVA 日期格式工具类DateUtil.java

    DateUtil.java package pers.kangxu.datautils.utils; import java.text.SimpleDateFormat; import java.ut ...

  8. 日期工具类 - DateUtil.java

    日期工具类,提供对日期的格式化和转换方法.获取区间日期.指定日期.每月最后一天等. 源码如下:(点击下载 -DateUtil.java.commons-lang-2.6.jar ) import ja ...

  9. 使用日期工具类:DateUtil

    利用java开发,避免不了String.Date转换,前一天.后一天等问题.给出一个工具类,仅供学习交流. import java.text.DateFormat; import java.text. ...

  10. android 工具类 DateUtil

    提取了一些在开发过程中可能会用到的日期相关的函数作为工具类.供大家參考: /** * 日期操作工具类. * * @author shimiso */ public class DateUtil { p ...

随机推荐

  1. React-Native 之 GD (二)自定义共用导航栏样式

    1.自定义导航栏样式 步骤一:从效果图中可以看出,导航栏的样式都差不多,因为我们前面已经设置了 Navigator ,这边的话我们还需要自定义 Navigator 的样式,可以看到所有的 Naviga ...

  2. UVALive 7325 Book Borders

    题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_ ...

  3. AtomicInteger 源码分析

    AtomicInteger AtomicInteger 能解决什么问题?什么时候使用 AtomicInteger? 支持原子更新的 int 值. 如何使用 AtomicInteger? 1)需要被多线 ...

  4. @TableLogic表逻辑处理注解(逻辑删除)

    在字段上加上这个注解再执行BaseMapper的删除方法时,删除方法会变成修改 例: 实体类:    @TableLogic private Integer del;   service层: 调用Ba ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_04-集合_06 Set集合_1_HashSet集合介绍

    特点:不允许有重复的记录,无序的集合 set不允许重复.接口中没有索引.所以方法和Collection中的方法是一样的,没有带索引的方法 因为Set的方法和Collection都是一样的.所以这里不再 ...

  6. Components controls 区别

    http://www.cnblogs.com/del/archive/2008/10/23/1317862.html 一个容器控件如果被其他控件指定为属主(Owner), 那么它的 Component ...

  7. ETCD分布式锁实现选主机制(Golang实现)

    ETCD分布式锁实现选主机制(Golang) 为什么要写这篇文章 做架构的时候,涉及到系统的一个功能,有一个服务必须在指定的节点执行,并且需要有个节点来做任务分发,想了半天,那就搞个主节点做这事呗,所 ...

  8. ecshop后台增加模块菜单详细教程

    我们有时候针对ecshop如此开发,想在后台加一些菜单,最模板以前提供过教程,但是并非很系统,今天最模板抛砖引玉图文教程告诉大家:如何在ecshop后台增加模块菜单! 首先需要修改四个文件:inc_p ...

  9. python笔记01(详情请看廖雪峰的官方网站)

    python 在调用函数的时候, 如果传入的参数数量不对, 如果传入的参数类型不对 会报TypeError的错误,并且Python会明确提示参数错误原因. hex()内置函数会把一个整数转换成十六进制 ...

  10. log记录日志使用说明

    一. 想要让Log4net日志(以下称日志)按每月自动归类为一个文件夹,为此,学习和修改了log4net.config文件.查了资料,重点是以下这些参数: <param name="F ...