/**
* 类描述:时间操作定义类
*/
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. getAttribute和getParameter

    getAttribute表示从request范围取得设置的属性,必须要先setAttribute设置属性,才能通过getAttribute来取得,设置与取得的为Object对象类型 getParame ...

  2. 大数据笔记(十六)——Hive的客户端及自定义函数

    一.Hive的Java客户端 JDBC工具类:JDBCUtils.java package demo.jdbc; import java.sql.DriverManager; import java. ...

  3. 模拟赛DAY 2 T1江城唱晚

    [题目背景] 墙角那株海棠,是你种下的思念. 生死不能忘,高烛照容颜. 一曲江城唱晚,重忆当年坐灯前, 青衫中绣着你留下的线. ——银临<江城唱晚> [问题描述] 扶苏是个喜欢一边听古风歌 ...

  4. (转)flexpaper 参数

    本文转载自:http://blog.csdn.net/z69183787/article/details/18659913 Flexpaper可能用到如下参数   SwfFile (String) 需 ...

  5. java设置RabbitMQ的消费处理出现:ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

    WARN 7868 --- [cTaskExecutor-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit messa ...

  6. Delphi XE2 之 FireMonkey 入门(29) - 数据绑定: TBindingsList: 表达式的 Evaluate() 方法

    Delphi XE2 之 FireMonkey 入门(29) - 数据绑定: TBindingsList: 表达式的 Evaluate() 方法 TBindingsList 中可能不止一个表达式, 通 ...

  7. jmeter之分布式压测

    很多性能大牛说一台机器的压测其实不准确,于是搜索网上的分布式压测练习了一番 目录 1.环境准备 2.控制机和压测机配置 3.执行分布式压测 1.环境准备 1.1准备一台windows作为控制机(mas ...

  8. Prometheus Alertmanager Grafana 监控警报

    Prometheus Alertmanager Grafana 监控警报 #node-exporter, Linux系统信息采集组件 #prometheus , 抓取.储存监控数据,供查询指标 #al ...

  9. PHP 实现并发-进程控制 PCNTL

    参考 基于PCNTL的PHP并发编程 PCNTL 是 PHP 中的一组进程控制函数,可以用来 fork(创建)进程,传输控制信号等. 在PHP中,进程控制支持默认关闭.编译时通过 --enable-p ...

  10. C语言第七周作业

    每个单词的最后一个字母改成大写 函数fun的功能是:将p所指字符串中每个单词的最后一个字母改成大写.(这里的"单词"是指由空格隔开的字符串). 函数接口定义: void fun( ...