I've been working on some code for a while and I can't seem to figure this bit out. I've got 5 spinners for each field of year, day of year, hour, minute, and second. My goal is to take those 5 parameters and use them to create a ZonedDateTime that can be sent out, but I have no clue where to go with this because of the difficulties of using the day of year format (which I can't change).
Asked
Active
Viewed 1,502 times
4 Answers
4
It’s not difficult when you know how:
ZonedDateTime dt = LocalDate.ofYearDay(2017, 86)
.atTime(16, 28, 55)
.atZone(ZoneId.systemDefault());
On my computer this gives 2017-03-27T16:28:55+02:00[Europe/Oslo]
.
Please substitute your five numbers into the places where I have given int literals. You may also want to substitute another time zone.

Ole V.V.
- 81,772
- 15
- 137
- 161
3
Given
int yr = ...;
int dayOfYear = ... ;
int hour = ... ;
int minute = ... ;
int second = ... ;
(which you can get from your spinners)
You can do
LocalDate date = Year.of(yr).atDay(dayOfYear);
LocalTime time = LocalTime.of(hour, minute, second);
ZonedDateTime zdt = ZonedDateTime.of(date, time, ZoneId.systemDefault());

James_D
- 201,275
- 16
- 291
- 322
1
Just use ZonedDateTime parse
method like that:
ZonedDateTime dt = ZonedDateTime.parse(
"2017 101 12:01:01",
DateTimeFormatter.ofPattern("yyyy DDD HH:mm:ss").withZone(
ZoneId.systemDefault()
)
);
Note that this will return a "date time" in the "system default" timezone (as it is not a part of your input pattern).
Also, the input value for the "day of the year", must be left-padded with zeroes, e.g.
31 => 031
You can do it (for example), like that:
String.format("%04d %03d %02d:%02d:%02d",year,doy,hour,minute,second)
(where year,doy,... are integer values from your spinners)

zeppelin
- 8,947
- 2
- 24
- 30
-
It seems a bit much to take 5 individual values, concatenate them into a string, and then parse the string back out, though... – James_D Mar 27 '17 at 14:41
0
Generate a LocalDateTime from the values you got from spinners and get a ZonedDateTime object
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm:ss.SSS a");
LocalDateTime ldt = LocalDateTime.of(2017, Month.JULY, 17, 19, 30, 15, 333);
ZonedDateTime zonedDateT = ZonedDateTime.of(ldt, ZoneId.of("Europe/Paris"));
System.out.println(zonedDateT.format(formatter));

ΦXocę 웃 Пepeúpa ツ
- 47,427
- 17
- 69
- 97
-
The asker asked to have the 5 numbers converted to a `ZonedDateTime`. Aren’t you doing the opposite? – Ole V.V. Mar 27 '17 at 14:25
-
1
-
1
-
Yeah, I don't have the day n month/month so this method doesn't fit the description, but thanks anyway! – mightynifty Mar 28 '17 at 12:39