Sam-T
Sam-T

Reputation: 1985

Java TimeZoneOffset time conversion

Using Jdk8. I am trying to convert time actually just hours of the day (like 1130) into DateTime. I am trying it 2 ways as below none of them work correctly. 1130 gets converted into 11:00 and another 3:00 none of them are correct. Is there also a 3rd way naming my Time Zone.

Long ltime = Long.parseLong("1130");
   Long  seconds = (ltime/100)*60*60;
   LocalDateTime tsutcDttime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
    LocalDateTime lclDttime =   LocalDateTime.ofInstant(Instant.ofEpochSecond(seconds), ZoneId.systemDefault());
 System.out.println("ZoneId.systemDefault: " +ZoneId.systemDefault());
 System.out.println("UTC LocalDateTime : "+ tsutcDttime); 
 System.out.println("Sys Def LocalDateTime : "+ lclDttime); 

ZoneId.systemDefault: America/Los_Angeles

UTC LocalDateTime : 1970-01-01T11:00

Sys Def LocalDateTime : 1970-01-01T03:00

This problem got solved by below.

Part2 of this problem For some of my time components I have a Date and for some other I don't (but I have to convert everything into datetime anyway.

How do I add the actual date when I have it? I am not seeing a method LocalDate (date)? For others will simply let default to 1970 unless a better soln exists. The below just puts the 1970 date:

LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(secondsOfDay, 0, ZoneOffset.UTC); 

But when I have a date I would like to add it to secondsOfDay and create my DateTime- How. Like Date = Jan 1 2016 + secondsOfDay

Thanks

Upvotes: 1

Views: 96

Answers (2)

greg-449
greg-449

Reputation: 111217

Assuming the string "1130" means 11 hours and 30 minutes you need to do the conversion to seconds separately for the hours and minutes:

long ltime = Long.parseLong("1130");

long hoursAsSeconds = (ltime / 100) * 60 * 60;
long minsAsSeconds = (ltime % 100) * 60;

long secondsOfDay = hoursAsSeconds + minsAsSeconds;

You can then use LocalTime to get the local time given the seconds:

LocalTime localTime = LocalTime.ofSecondOfDay(secondsOfDay);

You could also get the local time directly by parsing the time like this:

LocalTime localTime = LocalTime.parse("1130", DateTimeFormatter.ofPattern("HHmm"));

From that you can get a LocalDateTime using something like:

LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), localTime);

Or a ZonedDateTime using:

ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDate.now(), localTime, ZoneId.of("America/Los_Angeles"));

Upvotes: 2

Dominik Kunicki
Dominik Kunicki

Reputation: 1045

This expression is causing the issue:

 Long  seconds = (ltime/100)*60*60;

Division operator returns integer value so you are loosing precision here.

1130/100 = 11.3 ~ 11
11 * 60*60 = 39600
11.3 * 60*60 = 40680

Division should be the last operation in your expression:

Long  seconds = (ltime*60*60)/100;

Upvotes: 1

Related Questions