웹 프론트엔드 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 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP vs. Python : 차이점 이해 PHP vs. Python : 차이점 이해 Apr 11, 2025 am 12:15 AM

PHP와 Python은 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1.PHP는 간단한 구문과 높은 실행 효율로 웹 개발에 적합합니다. 2. Python은 간결한 구문 및 풍부한 라이브러리를 갖춘 데이터 과학 및 기계 학습에 적합합니다.

PHP : 웹 개발의 핵심 언어 PHP : 웹 개발의 핵심 언어 Apr 13, 2025 am 12:08 AM

PHP는 서버 측에서 널리 사용되는 스크립팅 언어이며 특히 웹 개발에 적합합니다. 1.PHP는 HTML을 포함하고 HTTP 요청 및 응답을 처리 할 수 ​​있으며 다양한 데이터베이스를 지원할 수 있습니다. 2.PHP는 강력한 커뮤니티 지원 및 오픈 소스 리소스를 통해 동적 웹 컨텐츠, 프로세스 양식 데이터, 액세스 데이터베이스 등을 생성하는 데 사용됩니다. 3. PHP는 해석 된 언어이며, 실행 프로세스에는 어휘 분석, 문법 분석, 편집 및 실행이 포함됩니다. 4. PHP는 사용자 등록 시스템과 같은 고급 응용 프로그램을 위해 MySQL과 결합 할 수 있습니다. 5. PHP를 디버깅 할 때 error_reporting () 및 var_dump ()와 같은 함수를 사용할 수 있습니다. 6. 캐싱 메커니즘을 사용하여 PHP 코드를 최적화하고 데이터베이스 쿼리를 최적화하며 내장 기능을 사용하십시오. 7

Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Feb 07, 2025 pm 12:09 PM

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

PHP 대 기타 언어 : 비교 PHP 대 기타 언어 : 비교 Apr 13, 2025 am 12:19 AM

PHP는 특히 빠른 개발 및 동적 컨텐츠를 처리하는 데 웹 개발에 적합하지만 데이터 과학 및 엔터프라이즈 수준의 애플리케이션에는 적합하지 않습니다. Python과 비교할 때 PHP는 웹 개발에 더 많은 장점이 있지만 데이터 과학 분야에서는 Python만큼 좋지 않습니다. Java와 비교할 때 PHP는 엔터프라이즈 레벨 애플리케이션에서 더 나빠지지만 웹 개발에서는 더 유연합니다. JavaScript와 비교할 때 PHP는 백엔드 개발에서 더 간결하지만 프론트 엔드 개발에서는 JavaScript만큼 좋지 않습니다.

PHP vs. Python : 핵심 기능 및 기능 PHP vs. Python : 핵심 기능 및 기능 Apr 13, 2025 am 12:16 AM

PHP와 Python은 각각 고유 한 장점이 있으며 다양한 시나리오에 적합합니다. 1.PHP는 웹 개발에 적합하며 내장 웹 서버 및 풍부한 기능 라이브러리를 제공합니다. 2. Python은 간결한 구문과 강력한 표준 라이브러리가있는 데이터 과학 및 기계 학습에 적합합니다. 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

PHP의 영향 : 웹 개발 및 그 이상 PHP의 영향 : 웹 개발 및 그 이상 Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

PHP : 많은 웹 사이트의 기초 PHP : 많은 웹 사이트의 기초 Apr 13, 2025 am 12:07 AM

PHP가 많은 웹 사이트에서 선호되는 기술 스택 인 이유에는 사용 편의성, 강력한 커뮤니티 지원 및 광범위한 사용이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 거대한 개발자 커뮤니티와 풍부한 자원이 있습니다. 3) WordPress, Drupal 및 기타 플랫폼에서 널리 사용됩니다. 4) 웹 서버와 밀접하게 통합하여 개발 배포를 단순화합니다.

PHP vs. Python : 사용 사례 및 응용 프로그램 PHP vs. Python : 사용 사례 및 응용 프로그램 Apr 17, 2025 am 12:23 AM

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

See all articles