问题
I have a date in utc second and its time zone offset in sec. I would like to convert it to date string in format yyyy-mm-dd using java8 ZoneOffset class. Below is the time in seconds and offset
long time = 1574962442,
long offset = 3600
Now i want to obtain date in below format using java-8 DateTime API ?
String date = 2019-11-28 // in yyyy-MM-dd
回答1:
You can use Instant from java-8 DateTime API to obtains an OffsetDateTime of Instant from epoch seconds with offset seconds
OffsetDateTime offsetDateTime = Instant.ofEpochSecond(time)
.atOffset(ZoneOffset.ofTotalSeconds(offset));
And the get LocalDate from it
LocalDate localdate = offsetDateTime.toLocalDate(); //2019-11-28
If you want string formatted output use DateTimeFormatter
String output = localdate.format(DateTimeFormatter.ISO_LOCAL_DATE);
回答2:
you can use java 8 LocalDateTime
APIs to achieve this.
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(1574962442, 0, ZoneOffset.ofTotalSeconds(3600));
// for format
String formatted = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
来源:https://stackoverflow.com/questions/59349957/how-to-convert-time-in-utc-second-and-timezone-offset-in-second-to-date-using-ja