Home > database >  Get current date as string in databricks using scala
Get current date as string in databricks using scala

Time:01-06

I want to get current date in Scala as a String. For example, today current date is 5th Jan. I want to store it as a new variable dynamically as below.

val currdate : String = “20220105”

When I am using val currdate = Calendar.getInstance.getTime then am not getting output in desired format as above.

CodePudding user response:

Why do you need it as String?
For a Spark query you could use java.sql.Timestamp directly.

This how you get it:

import java.sql.Timestamp
import java.text.SimpleDateFormat
import java.time.Instant

val now: Timestamp =
  Timestamp.from(Instant.now())

If you really want a formatted String:

val asString =
  new SimpleDateFormat("yyyyMMdd").format(now)

SimpleDateFormat is old and not thread-safe but should do the job.

CodePudding user response:

This is how it's done using the contemporary java.time library.

import java.time.LocalDate
import java.time.format.DateTimeFormatter

val currdate: String = 
  LocalDate.now.format(DateTimeFormatter.ofPattern("yyyyMMdd"))

Older utilities like Calendar and SimpleDate still work (mostly) but should be avoided.

  •  Tags:  
  • Related