问题
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