How to remove timezone when convert from Date to DateTime

纵饮孤独 提交于 2021-02-11 17:19:27

问题


I have a Date get from Database and I want convert it to DateTime and set it to begin day. I write it below:

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

But when I convert it add time zone after convert. newDate look like :

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

I have a question: How to convert it to begin day and remove timezone: Example I want to convert it look like:

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

How to convert it to beginDay and remove timezone: Thankyou


回答1:


UPDATE: Added Joda-Time version, since question was changed from java-8 to jodatime.


If you have a Joda-Time DateTime, then use 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

If you have "a Date get from Database", i.e. a java.sql.Date, then use 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

If you have a java.sql.Timestamp, use 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

If you have a java.util.Date, use 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


来源:https://stackoverflow.com/questions/52298962/how-to-remove-timezone-when-convert-from-date-to-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!