Java 日期格式工具类

方法如下

DateUtil 类

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List; public class DateUtil {
private static final String defaultDateFormatStr = "yyyy-MM-dd";// 系统默认的格式化字符串
private static final String defaultTimeFormatStr = "yyyy-MM-dd HH:mm:ss";// 系统默认的格式化字符串 /**
* 日期转字符串
*/
public static String dateToString(Date date, String formatStr) {
DateFormat df = new SimpleDateFormat(formatStr);
return df.format(date);
} /**
* 字符串转换到时间格式,自定义日期格式
*/
public static Date stringToDate(String dateStr, String formatStr) {
DateFormat sdf = new SimpleDateFormat(formatStr);
Date date = null;
try {
date = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
} /**
* 取得系统时间,格式为yyyy-MM-dd HH:mm:ss
*/
public static String getSystemTime() {
String strTime = "";
DateFormat df = new SimpleDateFormat(defaultTimeFormatStr);
strTime = df.format(new Date());
return strTime;
} /**
* 取得系统日期,格式为yyyy-MM-dd
*/
public static String getSystemDate() {
String strDate = "";
SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
strDate = df.format(new Date());
return strDate;
} /**
* 取得系统时间,日期格式为yyyyMMddHHmmss
*/
public static String getShortSystemTime() {
String strTime = "";
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
strTime = df.format(new Date());
return strTime;
} /**
* 取得系统短日期,yyyyMMdd
*/
public static String getShortSystemDate() {
String strTime = "";
DateFormat df = new SimpleDateFormat("yyyyMMdd");
strTime = df.format(new Date());
return strTime;
} /**
* 系统时间加减,自定义日期格式
*/
public static String getOperaDate(String date, int dayNum, String formatStr) {
Date dt = null;
SimpleDateFormat df = new SimpleDateFormat(formatStr);
try {
dt = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
GregorianCalendar gc = new GregorianCalendar();
assert dt != null;
gc.setTime(dt);
gc.add(Calendar.DATE, dayNum);
return df.format(gc.getTime());
} /**
* 系统时间加减,默认日期格式
*/
public static String getOperaDate(String date, int dayNum) {
return getOperaDate(date, dayNum, defaultDateFormatStr);
} /**
* 系统月份加减,自定义日期格式
*/
public static String getOperaMonth(String date, int monthNum, String formatStr) {
Date dt = null;
SimpleDateFormat df = new SimpleDateFormat(formatStr);
try {
dt = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
GregorianCalendar gc = new GregorianCalendar();
assert dt != null;
gc.setTime(dt);
gc.add(Calendar.MONTH, monthNum);
return df.format(gc.getTime());
} /**
* 系统月份加减,默认日期格式
*/
public static String getOperaMonth(String date, int monthNum) {
return getOperaMonth(date, monthNum, defaultDateFormatStr);
} /**
* 取得两个日期的时间差(天数),两个都是字符串,格式自定义
*/
public static int getDateDifference(String date1, String date2, String formatStr) {
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
ParsePosition pos = new ParsePosition(0);
ParsePosition pos1 = new ParsePosition(0);
Date dt1 = formatter.parse(date1, pos);
Date dt2 = formatter.parse(date2, pos1);
return (int) (dt2.getTime() - dt1.getTime()) / (3600 * 24 * 1000);
} /**
* 取得两个日期的时间差(天数),两个都是字符串,格式为 yyyy-MM-dd
*/
public static int getDateDifference(String date1, String date2) {
return getDateDifference(date1, date2, defaultDateFormatStr);
} /**
* 取得两个日期的时间差(小时),两个都是日期型
*/
public static int getHourDifference(Date date1, Date date2) {
return (int) (date2.getTime() - date1.getTime()) / (3600 * 1000);
} /**
* 取得两个日期的月份差
*/
public static int getMonthDifference(String date1, String date2, String formatStr) {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
return result == 0 ? 1 : Math.abs(result);
} /**
* 取得两个日期的月份差
*/
public static int getMonthDifference(String date1, String date2) {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat(defaultDateFormatStr);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c1.setTime(sdf.parse(date1));
c2.setTime(sdf.parse(date2));
} catch (ParseException e) {
e.printStackTrace();
}
result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
return result;
} /**
* 取得当月最后一天
*/
public static String getLastDayOfMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));// 年
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));// 月,因为Calendar里的月是从0开始,所以要减1
cal.set(Calendar.DATE, 1);// 日,设为一号
cal.add(Calendar.MONTH, 1);// 月份加一,得到下个月的一号
cal.add(Calendar.DATE, -1);// 下一个月减一为本月最后一天
return new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());
} /**
* 取得当月第一天
*/
public static String getFirstDayOfMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));// 年
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));// 月,因为Calendar里的月是从0开始,所以要减1
cal.set(Calendar.DATE, 1);// 日,设为一号
return new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());// 获得月初是几号
} /**
* 取得上个月的第一天
*/
public static String getFirstDayOfLastMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));// 年
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));// 月,因为Calendar里的月是从0开始,所以要减1
cal.set(Calendar.DATE, 1);// 日,设为一号
cal.add(Calendar.MONTH, -1);// 月份减一,得到上个月的一号
return new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());// 获得月初是几号
} /**
* 取得下个月的最后一天
*/
public static String getLastDayOfNextMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));// 年
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));// 月,因为Calendar里的月是从0开始,所以要减1
cal.set(Calendar.DATE, 1);// 日,设为一号
cal.add(Calendar.MONTH, 2);// 月份加一,得到下下个月的一号
cal.add(Calendar.DATE, -1);// 下下一个月减一为下个月最后一天
return new SimpleDateFormat(defaultDateFormatStr).format(cal.getTime());// 获得月末是几号
} /**
* 取得当月最后一天
*/
public static String getLastDayOfMonth(String date) {
Date dt = null;
SimpleDateFormat df = new SimpleDateFormat(defaultDateFormatStr);
try {
dt = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
assert dt != null;
cal.setTime(dt);
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));// 年
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));// 月,因为Calendar里的月是从0开始,所以要减1
cal.set(Calendar.DATE, 1);// 日,设为一号
cal.add(Calendar.MONTH, 1);// 月份加一,得到下个月的一号
cal.add(Calendar.DATE, -1);// 下一个月减一为本月最后一天
return df.format(cal.getTime());// 获得月末是几号
} /**
* 获取某个时间段的所有天数集合(包含起始日期与终止日期)
*/
public static List<String> getDayList(String starDate, String endDate) {
SimpleDateFormat format = new SimpleDateFormat(defaultDateFormatStr);
List<String> dayList = new ArrayList<String>();
if (starDate.equals(endDate)) {
dayList.add(starDate);
} else if (starDate.compareTo(endDate) < 0) {
while (starDate.compareTo(endDate) <= 0) {
dayList.add(starDate);
long l = stringToDate(starDate, "yyyy-MM-dd").getTime();
starDate = format.format(l + 3600 * 24 * 1000);
}
} else {
dayList.add(endDate);
}
return dayList;
}
}

DateUtilTest 类

import java.util.Date;

public class DateUtilTest {
public static void main(String[] args) {
// 日期转字符串
System.out.println("日期转字符串: " + DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
// 字符串转换到时间格式,自定义日期格式
System.out.println("字符串转换到时间格式,自定义日期格式: " + DateUtil.stringToDate("2019-02-20 09:49:22", "yyyy-MM-dd HH:mm"));
// 取得两个日期的时间差(天数),两个都是字符串,格式为 yyyy-MM-dd
System.out.println("取得两个日期的时间差(天数),两个都是字符串,格式为 yyyy-MM-dd: " + DateUtil.getDateDifference("2019-02-10", "2019-02-20"));
// 取得两个日期的时间差(天数),两个都是字符串,格式自定义
System.out.println("取得两个日期的时间差(天数),两个都是字符串,格式自定义: " + DateUtil.getDateDifference("2019-02-08 15:29:35", "2019-02-20 18:19:49", "yyyy-MM-dd HH:mm:ss"));
// 获取某个时间段的所有天数集合(包含起始日期与终止日期)
System.out.println("获取某个时间段的所有天数集合(包含起始日期与终止日期): " + DateUtil.getDayList("2019-02-09", "2019-02-19"));
// 取得上个月的第一天
System.out.println("取得上个月的第一天: " + DateUtil.getFirstDayOfLastMonth());
// 取得当月第一天
System.out.println("取得当月第一天: " + DateUtil.getFirstDayOfMonth());
// 取得两个日期的时间差(小时),两个都是日期型
System.out.println("取得两个日期的时间差(小时),两个都是日期型: " + DateUtil.getHourDifference(DateUtil.stringToDate("2019-02-20 09:49:22", "yyyy-MM-dd HH:mm:ss"), DateUtil.stringToDate("2019-02-20 12:10:16", "yyyy-MM-dd HH:mm:ss")));
// 取得当月最后一天
System.out.println("取得当月最后一天: " + DateUtil.getLastDayOfMonth());
// 取得当月最后一天
System.out.println("取得当月最后一天: " + DateUtil.getLastDayOfMonth("2019-03-20"));
// 取得下个月的最后一天
System.out.println("取得下个月的最后一天: " + DateUtil.getLastDayOfNextMonth());
// 取得两个日期的月份差
System.out.println("取得两个日期的月份差: " + DateUtil.getMonthDifference("2019-01-09", "2019-08-19"));
// 取得两个日期的月份差
System.out.println("取得两个日期的月份差: " + DateUtil.getMonthDifference("2019-05-19 18:19:49", "2019-08-20 09:49:22", "yyyy-MM-dd HH:mm:ss"));
// 系统时间加减,默认日期格式
System.out.println("系统时间加减,默认日期格式: " + DateUtil.getOperaDate("2019-02-09", 5));
// 系统时间加减,自定义日期格式
System.out.println("系统时间加减,自定义日期格式: " + DateUtil.getOperaDate("2019-02-20 09:54:31", 5, "yyyy-MM-dd HH:mm:ss"));
// 系统月份加减,默认日期格式
System.out.println("系统月份加减,默认日期格式: " + DateUtil.getOperaMonth("2019-02-09", 5));
// 系统月份加减,自定义日期格式
System.out.println("系统月份加减,自定义日期格式: " + DateUtil.getOperaMonth("2019-02-20 09:49:22", 5, "yyyy-MM-dd HH:mm:ss"));
// 取得系统短日期,yyyyMMdd
System.out.println("取得系统短日期,yyyyMMdd: " + DateUtil.getShortSystemDate());
// 取得系统时间,日期格式为yyyyMMddHHmmss
System.out.println("取得系统时间,日期格式为yyyyMMddHHmmss: " + DateUtil.getShortSystemTime());
// 取得系统日期,格式为yyyy-MM-dd
System.out.println("取得系统日期,格式为yyyy-MM-dd: " + DateUtil.getSystemDate());
// 取得系统时间,格式为yyyy-MM-dd HH:mm:ss
System.out.println("取得系统时间,格式为yyyy-MM-dd HH:mm:ss: " + DateUtil.getSystemTime());
}
}

运行结果

```
日期转字符串: 2019-04-14 22:26:55
字符串转换到时间格式,自定义日期格式: Wed Feb 20 09:49:00 CST 2019
取得两个日期的时间差(天数),两个都是字符串,格式为 yyyy-MM-dd: 10
取得两个日期的时间差(天数),两个都是字符串,格式自定义: 12
获取某个时间段的所有天数集合(包含起始日期与终止日期): [2019-02-09, 2019-02-10, 2019-02-11, 2019-02-12, 2019-02-13, 2019-02-14, 2019-02-15, 2019-02-16, 2019-02-17, 2019-02-18, 2019-02-19]
取得上个月的第一天: 2019-03-01
取得当月第一天: 2019-04-01
取得两个日期的时间差(小时),两个都是日期型: 2
取得当月最后一天: 2019-04-30
取得当月最后一天: 2019-03-31
取得下个月的最后一天: 2019-05-31
取得两个日期的月份差: 7
取得两个日期的月份差: 3
系统时间加减,默认日期格式: 2019-02-14
系统时间加减,自定义日期格式: 2019-02-25 09:54:31
系统月份加减,默认日期格式: 2019-07-09
系统月份加减,自定义日期格式: 2019-07-20 09:49:22
取得系统短日期,yyyyMMdd: 20190414
取得系统时间,日期格式为yyyyMMddHHmmss: 20190414222655
取得系统日期,格式为yyyy-MM-dd: 2019-04-14
取得系统时间,格式为yyyy-MM-dd HH:mm:ss: 2019-04-14 22:26:55
```

Java 日期格式工具类的更多相关文章

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

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

  2. java日期比较工具类

    package com.net.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.ut ...

  3. JAVA 日期处理工具类 DateUtils

    package com.genlot.common.utils; import java.sql.Timestamp;import java.text.ParseException;import ja ...

  4. 日期转换工具类 CommUtil.java

    package com.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.ut ...

  5. 巧用Java中Calendar工具类

    Java的JDK中提供了一系列好用的util工具类.Calendar就是java.util中用于处理日期的工具类.且该工具类易学易用实用. 工具类Calendar是抽象类. PS:为什么把Calend ...

  6. 时间日期转换工具类,获取当前时间YYYYMMDD24HHMISS、YYYYMMDDHHMISS

    YYYYMMDD24HHMISS:24小时制时间(显示上只是比YYYYMMDDHHMISS中间多了一个24),例:2018102224112440 YYYYMMDDHHMISS:12小时制时间,例20 ...

  7. java日期格式大全 format SimpleDateFormat(转)

    java日期格式大全 format SimpleDateFormat   /**    * 字符串转换为java.util.Date<br>    * 支持格式为 yyyy.MM.dd G ...

  8. 使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间。

    1.使用java的Calendar工具类获取到本月的第一天起始时间和最后一天结束时间. package com.fline.aic.utils; import java.text.DateFormat ...

  9. JavaSE-基础语法(二)-系统类(java.lang.*)和工具类(java.util.*)

    系统类(java.lang.*)和工具类(java.util.*) 一.系统类(java.lang.*) 这个包下包含java语言的核心类,如String.Math.System和Thread类等,使 ...

随机推荐

  1. php 多维数组,根据某个特定字段过滤重复值

    //假如 数据是这样的$arr=[ [ 'goods_name'=>'xxx', 'goods_id'=>111,],[ 'goods_name'=>'xxx', 'goods_id ...

  2. 打造简单OS-总目录

    1-汇编写入引导区,虚拟机启动步骤 (了解即可) 2-开机BIOS初始化与MBR操作系统引导详解 (了解即可) 3-MBR引导区转移加载简单程序(突破512限制)(了解即可) 4-loader硬盘加载 ...

  3. ros topic 命令

    #查看topic频率rostopic hz /xxx_imu_driver/imu #查看topic信息rostopic info /xxx_imu_driver/imu #查看topic数据rost ...

  4. imu 返回的数据

    Cheader: seq: 423038 stamp: secs: 1562058492 nsecs: 992359716 frame_id: imuorientation: x: 0.0026971 ...

  5. c++ 字符串转数字

    #字符串转整数 string ss="-99"; cout<< stoi(ss)<<endl;

  6. 解决JavaWeb项目报错:The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    明明有项目和文件,而且别的项目都可以运行,偏偏这个不能用,报错The origin server did not find a current representation for the targe ...

  7. Why use swap when there is more than enough RAM.

    Swappiness is a property of the Linux kernel that changes the balance between swapping out runtime m ...

  8. GO 类型断言

    在Go语言中,我们可以使用type switch语句查询接口变量的真实数据类型,语法如下: switch x.(type) { // cases } x必须是接口类型. 来看一个详细的示例: type ...

  9. 编程微语 2019-Autumn

    很多时候我们要的是[网页全屏],可是许多软件却做成了[浏览器全屏],不要一听到[全屏]就认为真的是传统意义上的全屏.拜托,老板(往往就是最大的产品经理).产品经理.程序员,想想,说清楚,做正确.某度文 ...

  10. HttpClient学习(一)—— 基本使用

    HttpClient是支持Http协议的客户端编程工具包. 一.简单使用 1.1 引入依赖 <dependency> <groupId>org.apache.httpcompo ...