时间的类型的相互转换(date/String)及时区的比较
String ->Date ->String
@Test public void date() throws ParseException{ String sdate = "01-01-2025"; SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.parse(sdate); System.out.println("--date--"+date); sdate = (new SimpleDateFormat("yyyy-MM-dd")).format(date); System.out.println("---String---"+sdate); }
打印结果:
--date--Wed Jan 01 00:00:00 CST 2025
---String---2025-01-01
XMLGregorianCalendar -> Date -> String
/** * 将Date类转换为XMLGregorianCalendar * @param date * @return */ 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 * @return */ public static Date xmlDate2Date(XMLGregorianCalendar cal){ return cal.toGregorianCalendar().getTime(); }
有关TimeZone的计算
/** * Convert the string date value to date value. * * @param format * - Time pattern for this date format. * @param dateStr * - String date value to be converted. * @return Date value for the input date string. */ public static Date getStrToGMTDate(final String format, final String timeZoneOffset, final String dateStr) throws ParseException { Date result = null; if (!StringUtils.isEmpty(dateStr)) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); TimeZone tz=TimeZone.getTimeZone(TIMEZONE_GMT+timeZoneOffset); simpleDateFormat.setTimeZone(tz); simpleDateFormat.applyPattern(format); simpleDateFormat.setLenient(false); result = simpleDateFormat.parse(dateStr); } return result; }
@Test public void date1() { String departureDateTimeStr = "2017-05-04 10:00"; LocalDateTime departureDateTime = LocalDateTime.parse(departureDateTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); ZoneOffset offset = ZoneOffset.of("+08:00"); long hours = Instant.now().until(departureDateTime.toInstant(offset), ChronoUnit.HOURS); // Check if the hour difference is more than 24 hours if (hours >= 24) { System.out.println("----------" + hours); } }
----------26
参考资料:
http://www.howsoftworks.net/javaapi/java.time/indexlocaldatetime.html
https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html