java日期工具类

今天遇到了日期转换知识,在网上搜集了一个测试例子,并且在自己电脑上测试了一下,顺便记载下来,便于以后查找:
封装工具类:
package dataDemo;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


/**
* 日期时间处理封装
*
*/
public class DateTime implements Comparable<DateTime>, Serializable {

private static final long serialVersionUID = 4715414577633839197L;
private Calendar calendar = Calendar.getInstance();
private SimpleDateFormat sdf = new SimpleDateFormat();

private final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private final String DEFAULT_TIME_PATTERN = "HH:mm:ss";

public DateTime() {
}

public DateTime(String dateStr) {
try {
parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
}
}

public DateTime(String dateStr, TimeZone timeZone) {
this(dateStr);
calendar.setTimeZone(timeZone);
}

public DateTime(String dateStr, String pattern) {
try {
parse(dateStr, pattern);
} catch (Exception e) {
e.printStackTrace();
}
}

public DateTime(String dateStr, String pattern, TimeZone timeZone) {
this(dateStr, pattern);
calendar.setTimeZone(timeZone);
}

public DateTime(int year, int month, int day, int hour, int minute, int second) {
calendar.set(year, month, day, hour, minute, second);
}

public DateTime(int year, int month, int day, int hour, int minute, int second, TimeZone timeZone) {
this(year, month, day, hour, minute, second);
calendar.setTimeZone(timeZone);
}

public DateTime(long milliSeconds) {
calendar.setTimeInMillis(milliSeconds);
}

public Calendar getCalendar() {
return calendar;
}

public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}

public Date getDate() {
return calendar.getTime();
}

public void setDate(Date date) {
calendar.setTime(date);
}

public int getYear() {
return calendar.get(Calendar.YEAR);
}

public void setYear(int year) {
calendar.set(Calendar.YEAR, year);
}

public int getMonth() {
return calendar.get(Calendar.MONTH);
}

public void setMonth(int month) {
calendar.set(Calendar.MONTH, month);
}

public int getDay() {
return calendar.get(Calendar.DAY_OF_MONTH);
}

public void setDay(int dayOfMonth) {
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}

public int getHour() {
return calendar.get(Calendar.HOUR_OF_DAY);
}

public void setHour(int hour) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
}

public int getMinute() {
return calendar.get(Calendar.MINUTE);
}

public void setMinute(int minute) {
calendar.set(Calendar.MINUTE, minute);
}

public int getSecond() {
return calendar.get(Calendar.SECOND);
}

public void setSecond(int second) {
calendar.set(Calendar.SECOND, second);
}

public long getTimeInMilliSeconds() {
return calendar.getTimeInMillis();
}

public void setTimeInMilliSeconds(long milliSeconds) {
calendar.setTimeInMillis(milliSeconds);
}

public TimeZone getTimeZone() {
return calendar.getTimeZone();
}

public void setTimeZone(TimeZone timeZone) {
calendar.setTimeZone(timeZone);
}

/**
* 使用默认格式解析日期字符串
*
* @param dateStr
* @throws Exception
*/
public void parse(String dateStr) throws Exception {
try {
parse(dateStr, DEFAULT_DATETIME_PATTERN);
} catch (Exception e) {
try {
parse(dateStr, DEFAULT_DATE_PATTERN);
} catch (Exception e1) {
try {
parse(dateStr, DEFAULT_TIME_PATTERN);
} catch (Exception e2) {
throw new Exception("the date string [" + dateStr + "] could not be parsed");
}
}
}

}

/**
* 使用给定模式解析日期字符串
*
* @param dateStr
* @param pattern
* @throws Exception
*/
public void parse(String dateStr, String pattern) throws Exception {
if (dateStr == null) {
throw new NullPointerException("date string could not be null");
}

if (pattern == null) {
throw new NullPointerException("the pattern string could not be null");
}

try {
sdf.applyPattern(pattern);
sdf.parse(dateStr);
} catch (ParseException e) {
throw new Exception("the date string [" + dateStr + "] could not be parsed with the pattern [" + pattern + "]");
}
calendar = sdf.getCalendar();
}

/**
* 格式化当前DateTime对象代表的时间
*
* @param pattern
* @return
*/
public String format(String pattern) {
sdf.applyPattern(pattern);
return sdf.format(calendar.getTime());
}

/**
* 获取默认格式日期字符串
*
* @return
*/
public String toDateTimeString() {
sdf.applyPattern(DEFAULT_DATETIME_PATTERN);
return sdf.format(calendar.getTime());
}

@Override
public int compareTo(DateTime otherDateTime) {
return calendar.compareTo(otherDateTime.getCalendar());
}

/**
* 是否闰年
*
* @return
*/
public boolean isLeapYear() {
int year = getYear();
boolean result = false;
if (year % 100 == 0) {
if (year % 400 == 0) {
result = true;
}
} else if (year % 4 == 0) {
result = true;
}
return result;
}

/**
* 获取星期
*
* @return
*/
public int getDayOfWeek() {
return calendar.get(Calendar.DAY_OF_WEEK);
}

/**
* 是否周末
*
* @return
*/
public boolean isWeekend() {
int dayOfWeek = getDayOfWeek();
return dayOfWeek == 1 || dayOfWeek == 7;
}

/**
* 当前DateTime对象月份天数
*
* @return
*/
public int getDayNumsInMonth() {
Calendar c = (Calendar) calendar.clone();
c.set(Calendar.DAY_OF_MONTH, 1);
c.roll(Calendar.DAY_OF_MONTH, -1);
return c.get(Calendar.DAY_OF_MONTH);
}

/**
* 两个日期之间间隔天数
*
* @param otherDateTime
* @return
*/
public int dayNumFrom(DateTime otherDateTime) {
long millis = Math.abs(getTimeInMilliSeconds() - otherDateTime.getTimeInMilliSeconds());
int days = (int) Math.floor(millis / 86400000);
return days;
}

public boolean lessThan(DateTime otherDateTime) {
return compareTo(otherDateTime) < 0;
}

public boolean greaterThan(DateTime otherDateTime) {
return compareTo(otherDateTime) > 0;
}

public boolean equal(DateTime otherDateTime) {
return compareTo(otherDateTime) == 0;
}

/**
* 当前时间基础上增加秒数(负数时为减)
*
* @param amount
*/
public void plusSecond(int amount) {
calendar.add(Calendar.SECOND, amount);
}

public void plusMinute(int amount) {
calendar.add(Calendar.MINUTE, amount);
}

public void plusHour(int amount) {
calendar.add(Calendar.HOUR, amount);
}

public void plusDays(int amount) {
calendar.add(Calendar.DAY_OF_MONTH, amount);
}

public void plusMonth(int amount) {
calendar.add(Calendar.MONTH, amount);
}

public void plusYear(int amount) {
calendar.add(Calendar.YEAR, amount);
}

public void plus(int year, int month, int day, int hour, int minute, int second) {
plusYear(year);
plusMonth(month);
plusDays(day);
plusHour(hour);
plusMinute(minute);
plusSecond(second);
}

}

测试类:
package dataDemo;


import java.util.Date;

public class DateTimeTest {

public static void main(String[] args) throws Exception {
DateTime dateTime = new DateTime();
DateTime dateTime2 = new DateTime("2013-12-12");
System.out.println("默认格式输出:" + dateTime.toDateTimeString());
System.out.println("是否闰年:" + dateTime.isLeapYear());
System.out.println("自定义格式输出:" + dateTime.format("yyyy-MM-dd"));
System.out.println("输出到毫秒:" + dateTime.format("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println("某月天数:" + dateTime.getDayNumsInMonth());
System.out.println("星期:" + dateTime.getDayOfWeek());//1:星期日,7:星期六
System.out.println("是否周末:" + dateTime.isWeekend());
System.out.println("相距:" + dateTime.dayNumFrom(dateTime2) + "天");

dateTime.plusMonth(1);
System.out.println("增加一个月后的datetime: " + dateTime.toDateTimeString());
dateTime.plus(0, 0, 2, 4, 4, 5);
System.out.println("增加 XXX后的datetime: " + dateTime.toDateTimeString());
System.out.println("毫秒数:" + dateTime.getTimeInMilliSeconds());

//DateTime转换为Date
Date date = dateTime.getDate();
System.out.println( dateTime.getTimeInMilliSeconds() == date.getTime());
}
}

输出结果:
默认格式输出:2013-09-26 09:26:22
是否闰年:false
自定义格式输出:2013-09-26
输出到毫秒:2013-09-26 09:26:22.078
某月天数:30
星期:5
是否周末:false
相距:76天
增加一个月后的datetime: 2013-10-26 09:26:22
增加 XXX后的datetime: 2013-10-28 13:30:27
毫秒数:1382938227078
true



补充内容:

package dataDemo;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class Demo {
/**
* 返回当前日期时间字符串<br>
* 默认格式:yyyy-mm-dd hh:mm:ss
*
* @return String 返回当前字符串型日期时间
*/
public static String getCurrentTime() {
String returnStr = null;
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
returnStr = f.format(date);
return returnStr;
}

/**
* 返回自定义格式的当前日期时间字符串
*
* @param format
* 格式规则
* @return String 返回当前字符串型日期时间
*/
public static String getCurrentTime(String format) {
String returnStr = null;
SimpleDateFormat f = new SimpleDateFormat(format);
Date date = new Date();
returnStr = f.format(date);
return returnStr;
}
/**
* 返回当前字符串型日期
*
* @return String 返回的字符串型日期
*/
public static String getCurDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = simpledateformat.format(calendar.getTime());
return strDate;
}
/**
* 返回当前TimeStamp字符串型日期
*
* @return
*/
public static String getCurrentTimestamp() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = simpledateformat.format(calendar.getTime());
return strDate;
}
/**
* 返回当前TimeStamp字符串型日期
*
* @return
*/
public static String getCurrentChinaData() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String strDate = simpledateformat.format(calendar.getTime());
return strDate;
}
/**
* 根据日期获取星期
*
* @param strdate
* @return
*/
public static String getWeekDayByDate(String strdate) {
final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
Date date = new Date();
try {
date = sdfInput.parse(strdate);
} catch (ParseException e) {
e.printStackTrace();
}
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek < 0)
dayOfWeek = 0;
return dayNames[dayOfWeek];
}

/**
* 合并字符串数组
*
* @param a
* 字符串数组0
* @param b
* 字符串数组1
* @return 返回合并后的字符串数组
*/
public static String[] mergeStringArray(String[] a, String[] b) {
if (a.length == 0 || a==null)
return b;
if (b.length == 0 || b==null)
return a;
String[] c = new String[a.length + b.length];
for (int m = 0; m < a.length; m++) {
c[m] = a[m];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}




}

测试类

package dataDemo;

import java.util.Date;
import java.text.SimpleDateFormat;

public class DemoTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
Demo demo=new Demo();
System.out.println(demo.getCurrentTime());
System.out.println(demo.getCurrentTime("2013-09-26"));
System.out.println(demo.getCurrentTime("2013年09月26日"));
System.out.println(demo.getCurDate());
System.out.println(demo.getCurrentTimestamp());
System.out.println(demo.getCurrentChinaData());
System.out.println(demo.getWeekDayByDate("2013-09-26"));
String[] a={"sddsds","dsfdssdf"};
String[] b={"q11111","dffddf"};
String[] c=demo.mergeStringArray(a, b);
System.out.println(c.length);
System.out.println(c[0]+"1111"+c[1]);
}

}

运行结果:
2013-09-26 15:28:40
2013-09-26
2013年09月26日
2013-09-26
2013-09-26 15:28:40
2013年09月26日 15:28:40
星期四
4
sddsds1111dsfdssdf
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值