Hackaholic
Hackaholic

Reputation: 19743

Scala TimeZone Issue

I am facing this issue, I set the timezone to UTC but it still Says IST.

>>> import java.util.Calendar
>>> import java.util.TimeZone
>>> val cal = Calendar.getInstance()
>>> cal.setTimeZone(TimeZone.getTimeZone("UTC"))
>>> cal.getTimeZone().getDisplayName()
res95: String = Coordinated Universal Time  # here i got UTC
>>> cal.getTime()
res97: java.util.Date = Thu Oct 08 13:13:17 IST 2015
                                            ^^^   
                                    why here IST insted of UTC???

Upvotes: 3

Views: 5448

Answers (1)

mattinbits
mattinbits

Reputation: 10428

The 'getTime' function returns you a java Date object, which does not have knowledge of the setTimeZone call you made to the Calendar object. the Date object has no concept of timezone, it is just a wrapper around milliseconds since the epoch. The output you're seeing is just the default toString representation used by the Scala REPL to describe the object. You can explicitly convert a Date object to String in a specific timezone using code such as the following:

import java.text.SimpleDateFormat
import java.util.{TimeZone, Date}

val formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
val date= new Date(1444291567242l); //java.util.Date = Thu Oct 08 09:06:07 BST 2015
val dateString = formatter.format(date); //String = 2015-10-08 08:06:07 UTC

Upvotes: 4

Related Questions