java日期工具类(Long型,Date型,yyyyMMdd型)等
- import java.sql.Timestamp;
- import java.text.ParsePosition;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.GregorianCalendar;
- import java.util.regex.Pattern;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- public class DateUtils {
- protected static Log logger = LogFactory.getLog(DateUtils.class);
- // 格式:年-月-日 小时:分钟:秒
- public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";
- // 格式:年-月-日 小时:分钟
- public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";
- // 格式:年月日 小时分钟秒
- public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";
- // 格式:年-月-日
- public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";
- // 格式:月-日
- public static final String SHORT_DATE_FORMAT = "MM-dd";
- // 格式:小时:分钟:秒
- public static final String LONG_TIME_FORMAT = "HH:mm:ss";
- //格式:年-月
- public static final String MONTG_DATE_FORMAT = "yyyy-MM";
- // 年的加减
- public static final int SUB_YEAR = Calendar.YEAR;
- // 月加减
- public static final int SUB_MONTH = Calendar.MONTH;
- // 天的加减
- public static final int SUB_DAY = Calendar.DATE;
- // 小时的加减
- public static final int SUB_HOUR = Calendar.HOUR;
- // 分钟的加减
- public static final int SUB_MINUTE = Calendar.MINUTE;
- // 秒的加减
- public static final int SUB_SECOND = Calendar.SECOND;
- static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四","星期五", "星期六" };
- @SuppressWarnings("unused")
- private static final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- public DateUtils() {}
- /**
- * 把符合日期格式的字符串转换为日期类型
- *
- * @param dateStr
- * @return
- */
- public static java.util.Date stringtoDate(String dateStr, String format) {
- Date d = null;
- SimpleDateFormat formater = new SimpleDateFormat(format);
- try {
- formater.setLenient(false);
- d = formater.parse(dateStr);
- } catch (Exception e) {
- // log.error(e);
- d = null;
- }
- return d;
- }
- /**
- * 把符合日期格式的字符串转换为日期类型
- */
- public static java.util.Date stringtoDate(String dateStr, String format,
- ParsePosition pos) {
- Date d = null;
- SimpleDateFormat formater = new SimpleDateFormat(format);
- try {
- formater.setLenient(false);
- d = formater.parse(dateStr, pos);
- } catch (Exception e) {
- d = null;
- }
- return d;
- }
- /**
- * 把日期转换为字符串
- *
- * @param date
- * @return
- */
- public static String dateToString(java.util.Date date, String format) {
- String result = "";
- SimpleDateFormat formater = new SimpleDateFormat(format);
- try {
- result = formater.format(date);
- } catch (Exception e) {
- // log.error(e);
- }
- return result;
- }
- /**
- * 获取当前时间的指定格式
- *
- * @param format
- * @return
- */
- public static String getCurrDate(String format) {
- return dateToString(new Date(), format);
- }
- /**
- *
- * @param dateStr
- * @param amount
- * @return
- */
- public static String dateSub(int dateKind, String dateStr, int amount) {
- Date date = stringtoDate(dateStr, FORMAT_ONE);
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- calendar.add(dateKind, amount);
- return dateToString(calendar.getTime(), FORMAT_ONE);
- }
- /**
- * 两个日期相减
- *
- * @param firstTime
- * @param secTime
- * @return 相减得到的秒数
- */
- public static long timeSub(String firstTime, String secTime) {
- long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
- long second = stringtoDate(secTime, FORMAT_ONE).getTime();
- return (second - first) / 1000;
- }
- /**
- * 获得某月的天数
- *
- * @param year
- * int
- * @param month
- * int
- * @return int
- */
- public static int getDaysOfMonth(String year, String month) {
- int days = 0;
- if (month.equals("1") || month.equals("3") || month.equals("5")
- || month.equals("7") || month.equals("8") || month.equals("10")
- || month.equals("12")) {
- days = 31;
- } else if (month.equals("4") || month.equals("6") || month.equals("9")
- || month.equals("11")) {
- days = 30;
- } else {
- if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
- || Integer.parseInt(year) % 400 == 0) {
- days = 29;
- } else {
- days = 28;
- }
- }
- return days;
- }
- /**
- * 获取某年某月的天数
- *
- * @param year
- * int
- * @param month
- * int 月份[1-12]
- * @return int
- */
- public static int getDaysOfMonth(int year, int month) {
- Calendar calendar = Calendar.getInstance();
- calendar.set(year, month - 1, 1);
- return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
- }
- /**
- * 获得当前日期
- *
- * @return int
- */
- public static int getToday() {
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.DATE);
- }
- /**
- * 获得当前月份
- *
- * @return int
- */
- public static int getToMonth() {
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.MONTH) + 1;
- }
- /**
- * 获得当前年份
- *
- * @return int
- */
- public static int getToYear() {
- Calendar calendar = Calendar.getInstance();
- return calendar.get(Calendar.YEAR);
- }
- /**
- * 返回日期的天
- *
- * @param date
- * Date
- * @return int
- */
- public static int getDay(Date date) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- return calendar.get(Calendar.DATE);
- }
- /**
- * 返回日期的年
- *
- * @param date
- * Date
- * @return int
- */
- public static int getYear(Date date) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- return calendar.get(Calendar.YEAR);
- }
- /**
- * 返回日期的月份,1-12
- *
- * @param date
- * Date
- * @return int
- */
- public static int getMonth(Date date) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(date);
- return calendar.get(Calendar.MONTH) + 1;
- }
- /**
- * 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数
- *
- * @param date1
- * Date
- * @param date2
- * Date
- * @return long
- */
- public static long dayDiff(Date date1, Date date2) {
- return (date2.getTime() - date1.getTime()) / 86400000;
- }
- /**
- * 比较两个日期的年差
- *
- * @param befor
- * @param after
- * @return
- */
- public static int yearDiff(String before, String after) {
- Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
- Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
- return getYear(afterDay) - getYear(beforeDay);
- }
- /**
- * 比较指定日期与当前日期的差
- *
- * @param befor
- * @param after
- * @return
- */
- public static int yearDiffCurr(String after) {
- Date beforeDay = new Date();
- Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
- return getYear(beforeDay) - getYear(afterDay);
- }
- /**
- * 比较指定日期与当前日期的差
- * @param before
- * @return
- */
- public static long dayDiffCurr(String before) {
- Date currDate = DateUtils.stringtoDate(currDay(), LONG_DATE_FORMAT);
- Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
- return (currDate.getTime() - beforeDate.getTime()) / 86400000;
- }
- /**
- * 获取每月的第一周
- * @param year
- * @param month
- * @return
- */
- public static int getFirstWeekdayOfMonth(int year, int month) {
- Calendar c = Calendar.getInstance();
- c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
- c.set(year, month - 1, 1);
- return c.get(Calendar.DAY_OF_WEEK);
- }
- /**
- * 获取每月的最后一周
- * @param year
- * @param month
- * @return
- */
- public static int getLastWeekdayOfMonth(int year, int month) {
- Calendar c = Calendar.getInstance();
- c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
- c.set(year, month - 1, getDaysOfMonth(year, month));
- return c.get(Calendar.DAY_OF_WEEK);
- }
- /**
- * 获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss"
- *
- * @return
- */
- public static String getNow() {
- Calendar today = Calendar.getInstance();
- return dateToString(today.getTime(), FORMAT_ONE);
- }
- /**
- * 根据生日获取星座
- *
- * @param birth
- * YYYY-mm-dd
- * @return
- */
- public static String getAstro(String birth) {
- if (!isDate(birth)) {
- birth = "2000" + birth;
- }
- if (!isDate(birth)) {
- return "";
- }
- int month = Integer.parseInt(birth.substring(birth.indexOf("-") + 1,
- birth.lastIndexOf("-")));
- int day = Integer.parseInt(birth.substring(birth.lastIndexOf("-") + 1));
- String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
- int[] arr = { 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22 };
- int start = month * 2 - (day < arr[month - 1] ? 2 : 0);
- return s.substring(start, start + 2) + "座";
- }
- /**
- * 判断日期是否有效,包括闰年的情况
- *
- * @param date
- * YYYY-mm-dd
- * @return
- */
- public static boolean isDate(String date) {
- StringBuffer reg = new StringBuffer("^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
- reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
- reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
- reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
- reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
- reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
- reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
- reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
- Pattern p = Pattern.compile(reg.toString());
- return p.matcher(date).matches();
- }
- /**
- * 取得指定日期过 months 月后的日期 (当 months 为负数表示指定月之前);
- *
- * @param date
- * 日期 为null时表示当天
- * @param month
- * 相加(相减)的月数
- */
- public static Date nextMonth(Date date, int months) {
- Calendar cal = Calendar.getInstance();
- if (date != null) {
- cal.setTime(date);
- }
- cal.add(Calendar.MONTH, months);
- return cal.getTime();
- }
- /**
- * 取得指定日期过 day 天后的日期 (当 day 为负数表示指日期之前);
- *
- * @param date
- * 日期 为null时表示当天
- * @param month
- * 相加(相减)的月数
- */
- public static Date nextDay(Date date, int day) {
- Calendar cal = Calendar.getInstance();
- if (date != null) {
- cal.setTime(date);
- }
- cal.add(Calendar.DAY_OF_YEAR, day);
- return cal.getTime();
- }
- /**
- * 取得距离今天 day 日的日期
- * @param day
- * @param format
- * @return
- * @author chenyz
- */
- public static String nextDay(int day, String format) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(new Date());
- cal.add(Calendar.DAY_OF_YEAR, day);
- return dateToString(cal.getTime(), format);
- }
- /**
- * 取得指定日期过 day 周后的日期 (当 day 为负数表示指定月之前)
- *
- * @param date
- * 日期 为null时表示当天
- */
- public static Date nextWeek(Date date, int week) {
- Calendar cal = Calendar.getInstance();
- if (date != null) {
- cal.setTime(date);
- }
- cal.add(Calendar.WEEK_OF_MONTH, week);
- return cal.getTime();
- }
- /**
- * 获取当前的日期(yyyy-MM-dd)
- */
- public static String currDay() {
- return DateUtils.dateToString(new Date(), DateUtils.LONG_DATE_FORMAT);
- }
- /**
- * 获取昨天的日期
- *
- * @return
- */
- public static String befoDay() {
- return befoDay(DateUtils.LONG_DATE_FORMAT);
- }
- /**
- * 根据时间类型获取昨天的日期
- * @param format
- * @return
- * @author chenyz
- */
- public static String befoDay(String format) {
- return DateUtils.dateToString(DateUtils.nextDay(new Date(), -1), format);
- }
- /**
- * 获取明天的日期
- */
- public static String afterDay() {
- return DateUtils.dateToString(DateUtils.nextDay(new Date(), 1),
- DateUtils.LONG_DATE_FORMAT);
- }
- /**
- * 取得当前时间距离1900/1/1的天数
- *
- * @return
- */
- public static int getDayNum() {
- int daynum = 0;
- GregorianCalendar gd = new GregorianCalendar();
- Date dt = gd.getTime();
- GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
- Date dt1 = gd1.getTime();
- daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
- return daynum;
- }
- /**
- * getDayNum的逆方法(用于处理Excel取出的日期格式数据等)
- *
- * @param day
- * @return
- */
- public static Date getDateByNum(int day) {
- GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
- Date date = gd.getTime();
- date = nextDay(date, day);
- return date;
- }
- /** 针对yyyy-MM-dd HH:mm:ss格式,显示yyyymmdd */
- public static String getYmdDateCN(String datestr) {
- if (datestr == null)
- return "";
- if (datestr.length() < 10)
- return "";
- StringBuffer buf = new StringBuffer();
- buf.append(datestr.substring(0, 4)).append(datestr.substring(5, 7))
- .append(datestr.substring(8, 10));
- return buf.toString();
- }
- /**
- * 获取本月第一天
- *
- * @param format
- * @return
- */
- public static String getFirstDayOfMonth(String format) {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.DATE, 1);
- return dateToString(cal.getTime(), format);
- }
- /**
- * 获取本月最后一天
- *
- * @param format
- * @return
- */
- public static String getLastDayOfMonth(String format) {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.DATE, 1);
- cal.add(Calendar.MONTH, 1);
- cal.add(Calendar.DATE, -1);
- return dateToString(cal.getTime(), format);
- }
- /**
- * @desc: 获取系统 Timestamp,如(2014-12-18 17:35:46.651)
- * @return Timestamp
- */
- public static Timestamp getCurrentSysTimestamp(){
- Timestamp d = new Timestamp(System.currentTimeMillis());
- return d;
- }
- //----------------------------------------以下是(Long和Date)(Long和yyyy-MM-dd)转换---------------------------------------------------
- /**
- * 获取当前时间的秒数 1970/01/01至今的秒数,,等于new Date().getTime()/1000
- * @param date
- * @return
- * @throws Exception
- */
- public static long getNowTimeStamp()
- {
- long stamp = 0L;
- Date date1 = new Date();
- Date date2 = null;
- try {
- date2 = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).parse("1970/01/01 08:00:00");
- } catch (Exception e) {
- e.printStackTrace();
- }
- stamp = (date1.getTime() - date2.getTime()) / 1000L;
- return stamp;
- }
- /**
- * 获取当前时间的毫秒数 1970/01/01至今的毫秒数,等于new Date().getTime()
- * @param date
- * @return
- * @throws Exception
- */
- public static long getNowTimeStampMs(){
- long stamp = 0L;
- Date date1 = new Date();
- Date date2 = null;
- try {
- date2 = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).parse("1970/01/01 08:00:00");
- } catch (Exception e) {
- e.printStackTrace();
- }
- stamp = (date1.getTime() - date2.getTime());
- return stamp;
- }
- /**
- * 时间转换成秒 1970/01/01至今的秒数(Date转long),等于new Date().getTime()/1000
- * @param date
- * @return
- * @throws Exception
- */
- public static long getTimeStampByDate(Date date)
- {
- long stamp = 0L;
- Date date1 = date;
- Date date2 = null;
- try {
- date2 = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).parse("1970/01/01 08:00:00");
- stamp = (date1.getTime() - date2.getTime()) / 1000L;
- } catch (Exception e) {
- stamp = 0L;
- }
- return stamp;
- }
- /**
- * 时间转换成秒 1970/01/01至今的豪秒数(Date转long)
- * @param date
- * @return
- * @throws Exception
- */
- public static long getTimeStampMsByDate(Date date)
- {
- long stamp = 0L;
- Date date1 = date;
- Date date2 = null;
- try {
- date2 = (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).parse("1970/01/01 08:00:00");
- stamp = (date1.getTime() - date2.getTime());
- } catch (Exception e) {
- stamp = 0L;
- }
- return stamp;
- }
- /**
- * 将时间由秒转换成指定格式,如(long转:yyyy-MM-dd HH:mm:ss)
- * @param second
- * @param format
- * @return
- * @throws Exception
- */
- public static String getYYYYByTimeStamp(Long second, String format)
- {
- if(second==null||second==0){
- return "";
- }
- Date da = null;
- try {
- da = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse("1970-01-01 08:00:00");
- } catch (Exception e) {
- e.printStackTrace();
- }
- Date date = new Date(da.getTime() + second * 1000L);
- return (new SimpleDateFormat(format)).format(date);
- }
- /**
- * 将时间由毫秒转换成指定格式,如(long转:yyyy-MM-dd HH:mm:ss)
- * @param second
- * @param format
- * @return
- * @throws Exception
- */
- public static String getYYYYbyTimeStampMs(Long second, String format)
- {
- if(second==null||second==0){
- return "";
- }
- Date da = null;
- try {
- da = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse("1970-01-01 08:00:00");
- } catch (Exception e) {
- e.printStackTrace();
- }
- Date date = new Date(da.getTime() + second );
- return (new SimpleDateFormat(format)).format(date);
- }
- /**
- * 1970/01/01至今的秒数转换成Date
- * @param TimeStamp
- * @return
- */
- public static Date getDateByTimeStamp(Long TimeStamp){
- return new Date(TimeStamp*1000);
- }
- /**
- * 1970/01/01至今的豪秒数转换成Date
- * @param TimeStampMs
- * @return
- */
- public static Date getDateByTimeStampMs(Long TimeStampMs){
- return new Date(TimeStampMs);
- }
- }
java日期工具类(Long型,Date型,yyyyMMdd型)等的更多相关文章
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
- java日期工具类DateUtil-续一
上篇文章中,我为大家分享了下DateUtil第一版源码,但就如同文章中所说,我发现了还存在不完善的地方,所以我又做了优化和扩展. 更新日志: 1.修正当字符串日期风格为MM-dd或yyyy-MM时,若 ...
- java日期工具类DateUtil-续二
该版本是一次较大的升级,农历相比公历复杂太多(真佩服古人的智慧),虽然有规律,但涉及到的取舍.近似的感念太多,况且本身的概念就已经很多了,我在网上也是查阅了很多的资料,虽然找到一些计算的方法,但都有些 ...
- java日期工具类DateUtil
一名优秀的程序员,不仅需要有着丰富解决问题的方案,还需要的便是代码的沉淀,这不仅有助于自己快速的开发程序,也有利于保证程序的健壮.那如何才能沉淀自己的”代码“呢?从自己编写util开始其实就是一个不错 ...
- java 日期工具类DateUtils
日期工具类DateUtils CreateTime--2017年5月27日08:48:00Author:Marydon DateUtils.java-对日期类的进一步封装 import java. ...
- JAVA 日期工具类的总结
一般,在项目中,我们会会经常使用到日期的各种方式的处理,在各个业务逻辑操作中,都需要相关的日期操作,因此,实现项目中的日期工具类的提出,还是十分重要的,下面,就项目中常用到的日期的相关操作方式,做了一 ...
- Java 日期工具类(日期,月份加减等)--转
package util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.C ...
- Java 日期格式化,Java 日期工具类,Java Date工具类
================================ ©Copyright 蕃薯耀 2020-01-19 https://www.cnblogs.com/fanshuyao/ import ...
- java 日期工具类
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; imp ...
随机推荐
- JavaWeb总结(一)—Servlet
一.Servlet生命周期 1.Servlet生命周期 Serlet加载---->实例化---->服务---->销毁 2.init() Servlet容器启动时:读取web.xml配 ...
- PHP对象相关知识点的总结
对象传递:一种说法是"PHP对象是通过引用传递的",更准确的说法是别名(标识符)传递,即它们都保存着同一个标识符(ID)的拷贝,这个标识符指向同一个对象的真正内容. <?ph ...
- Liferay中利用URL传参数
业务场景:现在有一个新闻系统,有两个页面,A是新闻列表页面/web/guest/home,B是新闻的详情页面/web/guest/newsview. 业务逻辑为:在A页面中,点击新闻的标题进入B页面, ...
- ASP.NET Core 网站在Docker中运行
Docker作为新一代的虚拟化方式,未来肯定会得到广泛的应用,传统虚拟机的部署方式要保证开发环境.测试环境.UAT环境.生产环境的依赖一致性,需要大量的运维人力,使用Docker我们可以实现一次部署, ...
- Twitter数据抓取的方法(二)
Scraping Tweets Directly from Twitters Search Page – Part 2 Published January 11, 2015 In the previo ...
- 利刃 MVVMLight 5:绑定在表单验证上的应用
表单验证是MVVM体系中的重要一块.而绑定除了推动 Model-View-ViewModel (MVVM) 模式松散耦合 逻辑.数据 和 UI定义 的关系之外,还为业务数据验证方案提供强大而灵活的支持 ...
- 程序设计 之 C#实现《拼图游戏》 (下) 原理篇
前言:在 http://www.cnblogs.com/labixiaohei/p/6698887.html 程序设计 之 C#实现<拼图游戏>(上),上传了各模块代码,而在本文中将详细剖 ...
- CF #284 div1 D. Traffic Jams in the Land 线段树
大意是有n段路,每一段路有个值a,通过每一端路需要1s,如果通过这一段路时刻t为a的倍数,则需要等待1s再走,也就是需要2s通过. 比较头疼的就是相邻两个数之间会因为数字不同制约,一开始想a的范围是2 ...
- MAC Mysql 重置密码
使用mac电脑,当mysql登录密码忘记时,需要重置密码.步骤如下: 1. 关闭当前正在运行的mysql进程. A.进入"偏好设置",选择mysql, 再选"stop m ...
- OpenGL 的空间变换(下):空间变换
通过本文的上篇 OpenGL 的空间变换(上):矩阵在空间几何中的应用 ,我们了解到矩阵的基础概念.并且掌握了矩阵在空间几何中的应用.接下来,我们将结合矩阵来了解 OpenGL 的空间变换. 在使用 ...