Java 8 中 Date与LocalDateTime、LocalDate、LocalTime互转
Java 8中 java.util.Date 类新增了两个方法,分别是from(Instant instant)和toInstant()方法
// Obtains an instance of Date from an Instant object.
public static Date from(Instant instant) {
try {
return new Date(instant.toEpochMilli());
} catch (ArithmeticException ex) {
throw new IllegalArgumentException(ex);
}
}
// Converts this Date object to an Instant.
public Instant toInstant() {
return Instant.ofEpochMilli(getTime());
}
这两个方法使我们可以方便的实现将旧的日期类转换为新的日期类,具体思路都是通过Instant当中介,然后通过Instant来创建LocalDateTime(这个类可以很容易获取LocalDate和LocalTime),新的日期类转旧的也是如此,将新的先转成LocalDateTime,然后获取Instant,接着转成Date,具体实现细节如下:
// 01. java.util.Date --> java.time.LocalDateTime
public void UDateToLocalDateTime() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
}
// 02. java.util.Date --> java.time.LocalDate
public void UDateToLocalDate() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalDate localDate = localDateTime.toLocalDate();
}
// 03. java.util.Date --> java.time.LocalTime
public void UDateToLocalTime() {
java.util.Date date = new java.util.Date();
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
LocalTime localTime = localDateTime.toLocalTime();
}
// 04. java.time.LocalDateTime --> java.util.Date
public void LocalDateTimeToUdate() {
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}
// 05. java.time.LocalDate --> java.util.Date
public void LocalDateToUdate() {
LocalDate localDate = LocalDate.now();
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}
// 06. java.time.LocalTime --> java.util.Date
public void LocalTimeToUdate() {
LocalTime localTime = LocalTime.now();
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
java.util.Date date = Date.from(instant);
}
转载自 https://www.cnblogs.com/exmyth/p/6425878.html
代码
导包
// import org.joda.time.format.DateTimeFormat;
// import org.joda.time.format.DateTimeFormatter;
maven 依赖
joda-time
joda-time
2.9.4
// timeList.get(i) = "2018-05-30 15:24:15.259"
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date parse = df.parse(timeList.get(i));
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
DateTime dt3 = DateTime.parse(timeList.get(i), formatter);
Date date = dt3.toDate();
结果 : date == parse
二者转为 long 类型 也相等
特别是在 JSON 互转的时候
用途,写在实体类的字段上
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
private Date lastUpdateDate;
日期之间的转化关系: 1,获取当前系统时间 Date date = new Date();
2,Date转为DateTime
DateTime dateTime = new DateTime(date.getTime());
3,DateTime转为Date
Date date = dateTime.toDate();
4,获取日期格式,
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
5,Date转换为String类型格式 String dateStr = df.format(new Date());
工具类 /**
* 返回当前日期时间字符串
* 默认格式: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;
}
/**
* 返回当前日期时间字符串
* 默认格式:yyyymmddhhmmss
*
* @return String 返回当前字符串型日期时间
*/
public static BigDecimal getCurrentTimeAsNumber() {
String returnStr = null;
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
returnStr = f.format(date);
return new BigDecimal(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;
}
/**
* 返回指定格式的字符型日期
* @param date
* @param formatString
* @return
*/
public static String Date2String(Date date, String formatString) {
if (G4Utils.isEmpty(date)) {
return null;
}
SimpleDateFormat simpledateformat = new SimpleDateFormat(formatString);
String strDate = simpledateformat.format(date);
return strDate;
}
/**
* 返回当前字符串型日期
*
* @param format
* 格式规则
*
* @return String 返回的字符串型日期
*/
public static String getCurDate(String format) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpledateformat = new SimpleDateFormat(format);
String strDate = simpledateformat.format(calendar.getTime());
return strDate;
}
/**
* 返回TimeStamp对象
*
* @return
*/
public static Timestamp getCurrentTimestamp() {
Object obj = TypeCaseHelper.convert(getCurrentTime(), "Timestamp", "yyyy-MM-dd HH:mm:ss");
if (obj != null)
return (Timestamp) obj;
else
return null;
}
/**
* 将字符串型日期转换为日期型
*
* @param strDate
* 字符串型日期
* @param srcDateFormat
* 源日期格式
* @param dstDateFormat
* 目标日期格式
* @return Date 返回的util.Date型日期
*/
public static Date stringToDate(String strDate, String srcDateFormat, String dstDateFormat) {
Date rtDate = null;
Date tmpDate = (new SimpleDateFormat(srcDateFormat)).parse(strDate, new ParsePosition(0));
String tmpString = null;
if (tmpDate != null)
tmpString = (new SimpleDateFormat(dstDateFormat)).format(tmpDate);
if (tmpString != null)
rtDate = (new SimpleDateFormat(dstDateFormat)).parse(tmpString, new ParsePosition(0));
return rtDate;
}
/**
* dp转px
*
* @param context
* @param
* @return
*/
public static float dp2px(Context context, int dpVal) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static float sp2px(Context context, float spVal) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* 屏幕宽度
*
* @param context
* @return
*/
public static int getDisplayWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
/**
* 屏幕高度
*
* @param context
* @return
*/
public static int getDisplayHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
//是否同月
public static boolean isEqualsMonth(DateTime dateTime1, DateTime dateTime2) {
return dateTime1.getMonthOfYear() == dateTime2.getMonthOfYear();
}
/**
* 第一个是不是第二个的上一个月,只在此处有效
*
* @param dateTime1
* @param dateTime2
* @return
*/
public static boolean isLastMonth(DateTime dateTime1, DateTime dateTime2) {
DateTime dateTime = dateTime2.plusMonths(-1);
return dateTime1.getMonthOfYear() == dateTime.getMonthOfYear();
}
/**
* 第一个是不是第二个的下一个月,只在此处有效
* @param dateTime1
* @param dateTime2
* @return
*/
public static boolean isNextMonth(DateTime dateTime1, DateTime dateTime2) {
DateTime dateTime = dateTime2.plusMonths(1);
return dateTime1.getMonthOfYear() == dateTime.getMonthOfYear();
}
/**
* 获得两个日期距离几个月
* @return
*/
public static int getIntervalMonths(DateTime dateTime1, DateTime dateTime2) {
return (dateTime2.getYear() - dateTime1.getYear()) * 12 + (dateTime2.getMonthOfYear() - dateTime1.getMonthOfYear());
}
/**
* 获得两个日期距离几周
*
* @param dateTime1
* @param dateTime2
* @return
*/
public static int getIntervalWeek(DateTime dateTime1, DateTime dateTime2) {
DateTime sunFirstDayOfWeek1 = getSunFirstDayOfWeek(dateTime1);
DateTime sunFirstDayOfWeek2 = getSunFirstDayOfWeek(dateTime2);
int days = Days.daysBetween(sunFirstDayOfWeek1, sunFirstDayOfWeek2).getDays();
if (days > 0) {
return (days + 1) / 7;
} else if (days < 0) {
return (days - 1) / 7;
} else {
return days;
}
}
/**
* 是否是今天
* @param dateTime
* @return
*/
public static boolean isToday(DateTime dateTime) {
return new DateTime().toLocalDate().equals(dateTime.toLocalDate());
}
/**
* 某月第一天是周几
*
* @return
*/
public static int getFirstDayOfWeekOfMonth(int year, int month) {
int dayOfWeek = new DateTime(year, month, 1, 0, 0, 0).getDayOfWeek();
if (dayOfWeek == 7) {
return 0;
}
return dayOfWeek;
}
//转化一周从周日开始
public static DateTime getSunFirstDayOfWeek(DateTime dateTime) {
if (dateTime.dayOfWeek().get() == 7) {
return dateTime;
} else {
return dateTime.minusWeeks(1).withDayOfWeek(7);
}
}
/**
* 通过年份和月份 得到当月的日子
*
* @param year
* @param month
* @return
*/
public static int getMonthDays(int year, int month) {
month++;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
return 29;
} else {
return 28;
}
default:
return -1;
}
}
/**
* 获取这个月有几行
*
* @param year
* @param month
* @return
*/
public static int getMonthRows(int year, int month) {
int size = getFirstDayOfWeekOfMonth(year, month) + getMonthDays(year, month) - 1;
return size % 7 == 0 ? size / 7 : (size / 7) + 1;
}
/**
* 返回当前月份1号位于周几
*
* @param year 年份
* @param month 月份,传入系统获取的,不需要正常的
* @return 日:1 一:2 二:3 三:4 四:5 五:6 六:7
*/
public static int getFirstDayWeek(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 1);
return calendar.get(Calendar.DAY_OF_WEEK);
}
public static int getYearByTimeStamp(long timeStamp) {
String date = timeStampToDate(timeStamp);
String year = date.substring(0, 4);
return Integer.parseInt(year);
}
public static String timeStampToDate(long timeStamp) {
Date date = new Date(timeStamp);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = simpleDateFormat.format(date);
return dateStr;
}
/**
* 获取当前日期是星期几
*
* @param dt
* @return 当前日期是星期几
*/
public static Integer getWeekOfDate(DateTime dt) {
// String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Integer[] weekDays = {0, 1, 2, 3, 4, 5, 6};
Calendar cal = Calendar.getInstance();
cal.setTime(dt.toDate());
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 获取一个日期加上天数得到最后的日期
*
* @param d 日期
* @param day 加的天数 如果天数是负数,即是减
* @return 当前日期是星期几
*/
public static Date addDate(Date d, long day) {
long time = d.getTime();
day = day * 24 * 60 * 60 * 1000;
time += day;
return new Date(time);
}
// 得到当前时间
Date currentDate = new Date();
DateTime dateTime = new DateTime(); // DateTime.now()
System.out.println(currentDate.getTime());
System.out.println(dateTime.getMillis());
// 指定某一个时间,如2016-08-29 15:57:02
Date oneDate = new Date(1472457422728L);
DateTime oneDateTime = new DateTime(1472457422728L);
DateTime oneDateTime1 = new DateTime(2016, 8, 29, 15, 57, 2, 728);
System.out.println(oneDate.toString());
System.out.println(oneDateTime.toString()); // datetime默认的输出格式为yyyy-MM-ddTHH:mm:ss.SSS
System.out.println(oneDateTime1.toString("MM/dd/yyyy hh:mm:ss.SSSa")); // 直接就可以输出规定的格式
// DateTime和Date之间的转换
Date convertDate = new Date();
DateTime dt1 = new DateTime(convertDate);
System.out.println(dt1.toString());
Date d1 = dt1.toDate();
System.out.println(d1.toString());
// DateTime和Calendar之间的转换
Calendar c1 = Calendar.getInstance();
DateTime dt2 = new DateTime(c1);
System.out.println(dt2.toString());
Calendar c2 = dt2.toCalendar(null); // 默认时区Asia/Shanghai
System.out.println(c2.getTimeZone());
// 时间格式化
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt3 = DateTime.parse("2016-08-29 13:32:33", formatter);
System.out.println(dt3.toString());
// 若是不指定格式,会采用默认的格式,yyyy-MM-ddTHH:mm:ss.SSS,若被解析字符串只到年月日,后面的时分秒会全部默认为0
DateTime dt4 = DateTime.parse("2016-08-29T");
System.out.println(dt4.toString());
// 输出locale 输出2016年08月29日 16:43:14 星期一
System.out.println(new DateTime().toString("yyyy年MM月dd日 HH:mm:ss EE", Locale.CHINESE));
// 计算两个日期间隔的天数
LocalDate start = new DateTime().toLocalDate();
LocalDate end = new LocalDate(2016, 8, 25);
System.out.println(Days.daysBetween(start ,end).getDays()); // 这里要求start必须早于end,否则计算出来的是个负数
// 相同的还有间隔年数、月数、小时数、分钟数、秒数等计算
// 类如Years、Hours等
// 对日期的加减操作
DateTime dt5 = new DateTime();
dt5 = dt5.plusYears(1) // 增加年
.plusMonths(1) // 增加月
.plusDays(1) // 增加日
.minusHours(1) // 减小时
.minusMinutes(1) // 减分钟
.minusSeconds(1); // 减秒数
System.out.println(dt5.toString());
// 判断是否闰月
DateTime dt6 = new DateTime();
DateTime.Property month = dt6.monthOfYear();
System.out.println(month.isLeap());