首页 web前端 js教程 服务端日期处理的类

服务端日期处理的类

Dec 10, 2016 am 09:36 AM
java

 package com.gbcom.system.utils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gbcom.op.util.Assert;
import com.hc.core.utils.XMLGregorianCalendarConversionUtils;
/**
 * 服务端日期处理的类
 * 
 */
public class DateUtil {
/**
* 日志记录器
*/
public static final Logger LOG = LoggerFactory.getLogger(DateUtil.class);
/**
* 给指定的日期增加指定的时间
* 
* @param date
*            日期
* @param field
*            如#Calendar.MONTH #Calendar.DAY
* @param amount
*            数目,如1 加一天 -1减一天
* @return 增加指定时间的日期
*/
public static Date add(Date date, int field, int amount) {
Calendar calendar = getCalendar(date);
calendar.add(field, amount);
return calendar.getTime();
}
/**
* 将传入的日期转换成今天的时间
* 
* @param date
*            传入的日期
* @return 返回今天的时间
*/
public static Date getTodayTime(Date date) {
Calendar cNow = getCalendar(new Date());
Calendar calendar = getCalendar(date);
calendar.set(Calendar.YEAR, cNow.get(Calendar.YEAR));
calendar.set(Calendar.MONTH, cNow.get(Calendar.MONTH));
calendar.set(Calendar.DAY_OF_YEAR, cNow.get(Calendar.DAY_OF_YEAR));
return calendar.getTime();
}
/**
* 返回指定日期是一周中的第几天
* 
* @param date
*            指定日期
* @return 返回指定日期是一周中的第几天
*/
public static int getWeek(Date date) {
Calendar calendar = getCalendar(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
/**
* Date转换成Calendar
* 
* @param date
*            Date
* @return Calendar
*/
public static Calendar getCalendar(Date date) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
/**
* 两个日期相减,date1-date2,取得相差几天
* 
* @param date1
*            日期1
* @param date2
*            日期2
* @return 取得相差几天
*/
public static int sub(Date date1, Date date2) {
Assert.notNull(date1);
Assert.notNull(date2);
long tem = date1.getTime() - date2.getTime();
return Integer.parseInt(String.valueOf(tem / (24 * 60 * 60 * 1000)));
}
/**
* 合并时间,
* 
* @param date
*            年月日
* @param time
*            时分秒
* @return 合并后的日期
*/
@SuppressWarnings("deprecation")
public static Date mergeDate(Date date, Date time) {
Calendar calendar = getCalendar(date);
calendar.set(Calendar.MINUTE, time.getMinutes());
calendar.set(Calendar.HOUR_OF_DAY, time.getHours());
return calendar.getTime();
}
/**
* 用默认风格把时间格式化成<code>yyyy-MM-dd HH:mm:ss</code> 的时间字符串
* 
* @author zhaishixi 2013-09-18
* @param date
*            时间字符串
* @return date
*/
public static String format(Object date) {
if (date != null) {
return DateFormat.getDateTimeInstance().format(date);
} else {
return null;
}
}
/**
* 用默认风格把时间格式化成制定格式如<code>( yyyy-MM-dd HH:mm:ss)</code> 的时间字符串
* 
* @author zhaishixi 2013-09-26
* @param date
*            时间字符串
* @param pattern
*            the pattern describing the date and time format
* @return date
*/
public static String format(Object date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (date != null) {
return sdf.format(date);
} else {
return null;
}
}
/**
* 用默认风格把date(Object 类型)按指定格式<code>pattern</code>格式化Date类型
* 
* @author zhaishixi 2013-09-26
* @param date
*            时间字符串 * @param pattern the pattern describing the date and
*            time format
* @return date
*/
public static Date parse(Object date, String pattern) {
Date fd = new Date();
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
fd = sdf.parse(date.toString());
} catch (ParseException e) {
LOG.error("parse date failed!", e);
}
return fd;
}
/**
* 用默认风格把date(Object 类型)按指定格式<code>pattern</code>格式化Date类型
* 
* @param date
*            要转换的日期
* @param pattern
*            格式
* @return 转换后的日期
*/
public static Date parseDate(Object date, String pattern) {
Date d = new Date();
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String format = sdf.format(date);
try {
d = sdf.parse(format);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
/**
* 计算出离<code>beginDate日期data</code>天的日期. <li>若datas小于0表示当前日期之前data天. <li>
* 若datas大于0表当前日期之后data天.
* 
* @author zhaishixi 2013-09-25
* @param beginDate
*            要计算的天数
* @param data
*            间隔
* @return 得到日期 格式:<code>yyyy-MM-dd HH:mm:ss</code>
*/
public static Date getDate(Date beginDate, int data) {
Calendar beginCal = Calendar.getInstance();
beginCal.setTimeInMillis(beginDate.getTime());
GregorianCalendar calendar = new GregorianCalendar(beginCal
.get(Calendar.YEAR), beginCal.get(Calendar.MONTH), beginCal
.get(Calendar.DATE), beginCal.get(Calendar.HOUR_OF_DAY),
beginCal.get(Calendar.MINUTE), beginCal.get(Calendar.SECOND));
calendar.add(GregorianCalendar.DATE, data);
return new Date(calendar.getTimeInMillis());
}
/**
* 将时间(单位为秒) 转化为 :时 :分 : 秒格式
* 
* 该time 并非 {@link Date#getTime()} ,单位为秒
* 
* @param time
*            long
* @return String
*/
public static String valueOfSecond(long time) {
long h = time / 3600;
long m = (time % 3600) / 60;
long s = (time % 3600) % 60;
String value = h + "Basic_hour" + ":" + m + "Basic_min" + ":" + s
+ "Basic_sec";
return value;
}
/**
* 将时间(单位为分钟) 转化为 :天:时 :分格式
* 
* 该time 并非 {@link Date#getTime()} ,单位为分钟
* 
* @param time
*            long
* @return String
*/
public static String valueOfMinute(long time) {
long d = time / (24 * 60);
long h = (time % (24 * 60)) / 60;
long m = (time % (24 * 60)) % 60;
String value = d + "Basic_day" + ":" + h + "Basic_hour" + ":" + m
+ "Basic_min";
return value;
}
/**
* 返回当前月前n个月或者后n个月的第一天
* 
* @param num
*            n个月 isPositive 为true表示前,为false表示后
* @param isPositive
*            +/-
* @return n个月第一天
*/
@SuppressWarnings("deprecation")
public static Date getFirstDayOfMonth(int num, boolean isPositive) {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
int year = calendar.getTime().getYear();
int month = calendar.getTime().getMonth();
if (isPositive) {
month = month + num;
} else {
month = month - num;
}
int day = 1;
if (month < 0) {
year = year - 1;
month = 11;
} else if (month > 12) {
year = year + 1;
month = 0;
}
date = new Date(year, month, day);
return date;
}
// ----------------非通用方法,谨慎使用----------------//
/**
* 时间格式转换--cxf不识别java.sql.Timestamp
* 
* @param orgTime
*            java.sql.Timestamp
* @return XMLGregorianCalendar
*/
public static XMLGregorianCalendar timeToXmlDate(java.sql.Timestamp orgTime) {
if (orgTime != null) {
return XMLGregorianCalendarConversionUtils
.asXMLGregorianCalendar(new Date(orgTime.getTime()));
}
return null;
}
/**
* 将xmldate转为timestamp
* 
* @param cal
*            XMLGregorianCalendar
* @return java.sql.Timestamp
*/
public static java.sql.Timestamp xmlDate2Time(XMLGregorianCalendar cal) {
if (cal != null) {
return new java.sql.Timestamp(XMLGregorianCalendarConversionUtils
.asDate(cal).getTime());
}
return null;
}
/**
* 将Date类转换为XMLGregorianCalendar
* 
* @param date
*            Date
* @return XMLGregorianCalendar
*/
public static XMLGregorianCalendar dateToXmlDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
DatatypeFactory dtf = null;
try {
dtf = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
}
XMLGregorianCalendar dateType = dtf.newXMLGregorianCalendar();
dateType.setYear(cal.get(Calendar.YEAR));
// 由于Calendar.MONTH取值范围为0~11,需要加1
dateType.setMonth(cal.get(Calendar.MONTH) + 1);
dateType.setDay(cal.get(Calendar.DAY_OF_MONTH));
dateType.setHour(cal.get(Calendar.HOUR_OF_DAY));
dateType.setMinute(cal.get(Calendar.MINUTE));
dateType.setSecond(cal.get(Calendar.SECOND));
return dateType;
}
/**
* 将XMLGregorianCalendar转换为Date
* 
* @param cal
*            XMLGregorianCalendar
* @return Date
*/
public static Date xmlDate2Date(XMLGregorianCalendar cal) {
return cal.toGregorianCalendar().getTime();
}
/**
* 获取工作时间:8:30 - 17:30
* 
* @param date
*            String
* @return String[]
* @throws ParseException
*             ParseException
*/
public static String[] getWorkDate(String date) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cd = Calendar.getInstance();
cd.setTime(simpleDateFormat.parse(date));
cd.add(Calendar.HOUR, 7);
cd.add(Calendar.MINUTE, 30);
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String[] workDate = new String[2];
workDate[0] = simpleDateFormat.format(cd.getTime());
cd.add(Calendar.HOUR, 10);
workDate[1] = simpleDateFormat.format(cd.getTime());
return workDate;
}
/**
* 获取当天的开始时间
* 
* @param date
*            指定日期
* @return 当前开始日期
*/
public static Date getCurDayStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 获取本周的开始时间
* 
* @param date
*            指定日期
* @return 本周开始日期
*/
public static Date getCurWeekStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return calendar.getTime();
}
/**
* 获取当月的开始时间
* 
* @param date
*            指定日期
* @return 当月开始日期
*/
public static Date getCurMonthStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 获取当年的开始日期
* 
* @param date
*            指定日期
* @return 当年的开始日期
*/
public static Date getCurYearStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_YEAR, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
public static Date longToDate(long lg){
//long ,转 date
return new Date(lg);
}
public static long DateToLong(Date date){
return date.getTime();
}
/**
* date对象指向的实体却是一个Timestamp,即date拥有Date类的方法,但被覆盖的方法的执行实体在Timestamp中。
* : (DateUtil.tsToDate)
* @param ts
* @return
*/
public static Date tsToDate(Timestamp ts){
  Date date = new Date();  
       try {  
           date = ts;  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       return date;
}
public static Timestamp DateToTs(Date date){
Timestamp ts = new Timestamp(date.getTime());
 
return ts;
}
// off checkstyle
public static void main(String[] args) {
System.out.println(new Date());
System.out.println(new Date(System.currentTimeMillis()));
System.out.println(System.currentTimeMillis());
System.out.println(new Date(System.currentTimeMillis()).getTime());
System.out.println(new Date(System.currentTimeMillis()).getTime());
// //
// System.out.println(format(parse("20131111235959","yyyyMMddHHmmss")));
//
// // LOG.info("DATA="+parse("TTT20131111235959","dsdsdsd"));
// long var = 10201;
// System.out.println(valueOfMinute(var));
// System.out.println(valueOfSecond(var));
//
//
//
// Timestamp curTime = new Timestamp(System.currentTimeMillis());
// XMLGregorianCalendar calendar = timeToXmlDate(curTime);
//
// System.out.println("calendar = " + calendar);
//
// Timestamp timestamp = xmlDate2Time(calendar);
// System.out.println("timestamp = " +
// DateTimeHelper.formatTimeGBK(timestamp));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(getCurWeekStart(new Date()));
System.out.println(time);
}
}
登录后复制

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1673
14
CakePHP 教程
1429
52
Laravel 教程
1333
25
PHP教程
1278
29
C# 教程
1257
24
PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

突破或从Java 8流返回? 突破或从Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能 PHP与Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP的影响:网络开发及以后 PHP的影响:网络开发及以后 Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP与Python:用例和应用程序 PHP与Python:用例和应用程序 Apr 17, 2025 am 12:23 AM

PHP适用于Web开发和内容管理系统,Python适合数据科学、机器学习和自动化脚本。1.PHP在构建快速、可扩展的网站和应用程序方面表现出色,常用于WordPress等CMS。2.Python在数据科学和机器学习领域表现卓越,拥有丰富的库如NumPy和TensorFlow。

PHP:许多网站的基础 PHP:许多网站的基础 Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

See all articles