Reputation: 4999
I am trying to use SimpleDateFormat to parse a Date and Time string in scala. I want the Date object which is created to be in UTC format but it converts it into my Local Timezone. Setting Timezone or calendar is not working.
scala> new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
scala> res41.parse("2014-12-12 13:12:45")
//java.util.Date = Fri Dec 12 13:12:45 IST 2014
After setting Timezone like res41.setTimeZone(java.util.TimeZone.getTimeZone("UTC"))
(res41 is the instance of SimpleDateFormat in Scala REPL) gives me the same result.
If I set Calendar
, like res41.setCalendar(cal)
where cal
is an instance of java.util.Calendar
with Timezone as UTC also, does not change the result.
I am not sure what I am doing wrong.
Upvotes: 0
Views: 877
Reputation: 3522
You can use the java.time package built into Java 8. It is much easier to use than java.util classes.
import java.time.ZoneId
java.time.LocalDateTime.now()
java.time.LocalDateTime.now(ZoneId.of("GMT"))
java.time.LocalDateTime.now(ZoneId.of("Asia/Kolkata"))
java.time.LocalDateTime.now(ZoneId.of("Australia/Sydney"))
Using ZoneId
, it is possible to get the time for different time zones. Use proper time zone names.
You could also use Joda-Time, especially if you are not using Java 8. See DateTimeZone
.
Upvotes: 2