Java如何将Joda-Time的DateTime转换为Calendar或Date对象?
这段代码告诉你如何乔达时间的转换DateTime对象为JDK的java.util.Calendar或java.util.Date对象。要转换DateTime为java.util.Date使用toDate()方法,要转换为java.util.Calendar使用toCalendar()方法。
package org.nhooo.example.joda; import org.joda.time.DateTime; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class DateTimeToDateCalendarDemo { public static void main(String[] args) { //将DateTime对象转换为JDK的Date。 DateTime dateTime = DateTime.now(); Date date = dateTime.toDate(); System.out.println("dateTime = " + dateTime); System.out.println("date = " + date); //将DateTime对象转换为JDK的Calendar。 Calendar calendar = dateTime.toCalendar(Locale.getDefault()); System.out.println("calendar = " + calendar); } }
我们的代码片段的结果:
dateTime = 2019-07-22T13:48:13.005+08:00 date = Mon Jul 22 13:48:13 WITA 2019 calendar = java.util.GregorianCalendar[time=1563774493005,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Makassar",offset=28800000,dstSavings=0,useDaylight=false,transitions=5,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=203,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=48,SECOND=13,MILLISECOND=5,ZONE_OFFSET=28800000,DST_OFFSET=0]
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=joda-time/joda-time/2.10.3/joda-time-2.10.3.jar --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.3</version> </dependency>