Search code examples
javascaladatetimetimestampjodatime

How to get current time in Scala in timestamp/datetime format so that it can be stored in PG table


I have written the following function in Scala which works:

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


val curr_timeFmt = "YYYY_MM_dd_HH_mm_ss"

def curr_time(): String = {
    val date = new Date
    val currTS = new SimpleDateFormat(curr_timeFmt)
    currTS.setTimeZone(TimeZone.getTimeZone("EST"));
    currTS.format(date)
  }

I would like to store the return value from this function as a timestamp in a PG columnn of type timestamp.

Furthermore, while researching online, I heard that the the Java Calendar and Date classes are not thread safe and mutable. Is this true, if so how can I use the new joda time in Java 8?

Any help would be greatly appreciated, as Ive been looking online for a while and tried a few things and nothing seemed to work.

Thx


Solution

  • To get the current time in US Eastern time zone, in that format, using Java 8 Time API:

    val fmt = DateTimeFormatter.ofPattern("uuuu_MM_dd_HH_mm_ss")
    val time = LocalDateTime.now(ZoneId.of("America/New_York")).format(fmt)
    

    Printing value of time shows e.g.

    2019_03_18_21_32_22