0

I am doing a simple exercise in Scala trying to convert Moscow time to London and NY

import java.text.SimpleDateFormat
import java.util.TimeZone
inputFormat.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))
val inMoscow = inputFormat.parse("2020-03-19 12:44 Z")
inMoscow: java.util.Date = Thu Mar 19 12:44:00 MSK 2020 

Let's try to convert time representation to London:

val outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm Z")
outputFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"))
val outLondon = outputFormat.format(inMoscow)
outputFormat: SimpleDateFormat = java.text.SimpleDateFormat@c07fb1f4
outLondon: String = "2020-03-19 09:44 +0000"

Everything works as expected. However when I try to convert to NY time I get an unexpected results:

val outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm")
outputFormat.setTimeZone(TimeZone.getTimeZone("Americas/New_York"))
val outNY = outputFormat.format(inMoscow)
outputFormat: SimpleDateFormat = java.text.SimpleDateFormat@ba23d43a
outNY: String = "2020-03-19 09:44"

Same as London. What have I missed? Thanks in advance!

Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
  • 2
    I recommend you don’t use `SimpleDateFormat` and `TimeZone`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. In this case it’s `TimeZone` playing a trick on you. Instead use `DateTimeFormatter` and `ZoneId`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 20 '19 at 09:59
  • @OleV.V. can you show a modern time example of time zone conversion? – Sergey Bushmanov Mar 20 '19 at 11:57
  • 1
    It’s described in many places. For example [Java 8 timezone conversions](https://stackoverflow.com/questions/25885591/java-8-timezone-conversions). Search for [java 8 convert time-zone] or something similar. Also look at the use of `withZoneSameInstant` in [the Oracle tutorial](https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html). – Ole V.V. Mar 20 '19 at 12:34

1 Answers1

6

Are you sure that timezone is Americas/New_York. I think it is America/New_York, i.e. without s in America.

vavasthi
  • 922
  • 5
  • 14