从 Date 转换为 DateTime 时如何删除时区

How to remove timezone when convert from Date to DateTime

我有一个从数据库中获取的日期,我想将其转换为 DateTime 并将其设置为开始日期。我写在下面:

Date fromDate = studentDateJoin.getDate();
//result: fromDate = Mon Jan 01 00:00:02 ICT 2018
//convert to DateTime 
DateTime newDate = new DateTime(fromDate);

但是当我转换它时在转换后添加时区。新日期看起来像:

newDate = 2018-01-01T14:13:04.574Z+7

我有一个问题:如何将其转换为开始日并删除时区:示例我想将其转换为:

 //Convert it begin day and remove time zone
 newDate = 2018-01-01T00:00:00.00;

如何将其转换为 beginDay 并删除时区:谢谢

更新: 添加了 Joda-Time 版本,因为问题已从 java-8 更改为 jodatime


如果您有 Joda-Time DateTime,则使用 toLocalDate() and toLocalDateTime(...):

DateTime dateTime = new DateTime(2018, 1, 1, 14, 13, 04, 574);
System.out.println(dateTime);
LocalDate localDate = dateTime.toLocalDate();
System.out.println(localDate);
LocalDateTime localDateTime = localDate.toLocalDateTime(LocalTime.MIDNIGHT);
System.out.println(localDateTime);
2018-01-01T14:13:04.574-05:00
2018-01-01
2018-01-01T00:00:00.000

如果您有 "a Date get from Database",即 java.sql.Date,则使用 toLocalDate() and atStartOfDay():

java.sql.Date sqlDate = new java.sql.Date(118, 0, 1);
System.out.println(sqlDate);
LocalDate localDate = sqlDate.toLocalDate();
System.out.println(localDate);
LocalDateTime localDateTime = localDate.atStartOfDay();
System.out.println(localDateTime);
2018-01-01
2018-01-01
2018-01-01T00:00

如果你有 java.sql.Timestamp,请使用 toLocalDateTime() and truncatedTo(...):

java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(118, 0, 1, 14, 13, 04, 574000000);
System.out.println(sqlTimestamp);
LocalDateTime localDateTime = sqlTimestamp.toLocalDateTime();
System.out.println(localDateTime);
localDateTime = localDateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(localDateTime);
2018-01-01 14:13:04.574
2018-01-01T14:13:04.574
2018-01-01T00:00

如果您有 java.util.Date,请使用 toInstant(), atZone(...), toLocalDate(), and atStartOfDay():

java.util.Date utilDate = new java.util.Date(118, 0, 1, 14, 13, 04);
System.out.println(utilDate);
Instant instant = utilDate.toInstant();
System.out.println(instant);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
System.out.println(zonedDateTime);
LocalDateTime localDateTime = zonedDateTime.toLocalDate().atStartOfDay();
System.out.println(localDateTime);
Mon Jan 01 14:13:04 EST 2018
2018-01-01T19:13:04Z
2018-01-01T14:13:04-05:00[America/New_York]
2018-01-01T00:00