0

for example, now it is 2020-03-16 11:23:23.121 in Vietnam, but my program is running in the USA, how to get a Date instance which is 2020-03-16 12:00:00.000 in Vietnam, which mean, I keep the year, month, day as the same, but set hour as 12, minute, second and nanosecond as 0, can LocalDateTime play a role?

lily
  • 515
  • 7
  • 20

3 Answers3

3
ZonedDateTime zdt = ZonedDateTime.of(2020, 3, 16, 12, 0, 0, 0, ZoneId.of("Asia/Ho_Chi_Minh"));
Oleg
  • 6,124
  • 2
  • 23
  • 40
2

ZonedDateTime

From java-8 you can use ZonedDateTime to get the date time from any zone

ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("Asia/Ho_Chi_Minh"))

And the you can modify the time to 12:00:00 using with method. Pass the time of day as a LocalTime object obtained by calling LocalTime.of. In the new LocalTime object, the second and the nanosecond default to zero, so no need to pass those arguments to the factory method.

dateTime.with( LocalTime.of( 12 , 0 ) )  //2020-03-16T12:00+07:00[Asia/Ho_Chi_Minh]

Java util Date will not store any time zone information and it just represents a specific instant in time (which is only UTC), with millisecond precision. I will suggest to avoid using legacy util.Date

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • can LocalDateTime play a role? – lily Mar 16 '20 at 03:43
  • For me OP requirement is not clear and for me it seems he needs to get date time from one zone and convert it into `util.Date`, `LocalDateTime` can help if he just need date and time from Vietnam @lily – Ryuzaki L Mar 16 '20 at 03:46
  • now, I want to keep year, month, day as the same, but set hour as 12, and all other parts below it, like minute, second, nanosecond as 0 in Vietnam onetime – lily Mar 16 '20 at 03:48
0

No, do not use LocalDateTime here

can LocalDateTime play a role?

LocalDateTime cannot represent a moment, as it lacks the context of a time zone or offset-from-UTC. So that is exactly the wrong classs to use here on your Question.

To represent a moment, a specific point on the timeline, use:

  • Instant (always in UTC)
  • OffsetDateTime (carries an offset-from-UTC, a number of hours-minutes-seconds)
  • ZonedDateTime (carries an assigned time zone, named in Continent/Region)

See the correct Answer by Deadpool showing the proper use of ZonedDateTime to solve your problem.

For more info, see What's the difference between Instant and LocalDateTime?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154